C#WinForms应用程序 - 调试错误 - 长度不能小于零。参数名称:长度

时间:2011-03-31 14:17:10

标签: c# winforms debugging error-handling process

在调试模式下,在运行C#WinForms应用程序时,我通过OpenFileDialog成功选择多个文件,然后显示在日志记录窗口中,这些文件被复制到临时目录中,我相信我在尝试时遇到错误将excel文件转换为csv。我收到以下运行时调试错误:

Error: You may not have permission to read the file or it may be corrupt. 
Reported Error: Length Can not be less than zero. 
Parameter Name: Length.

如何修复此错误?

这是我在MainForm.cs上的代码

            // Consolidate Button Click Commands that executes if there are no user input errors 
    void ExecuteConsolidate()
    {
        string consolidatedFolder = targetFolderBrowserDialog.SelectedPath;
        string tempfolder = targetFolderBrowserDialog.SelectedPath + "\\tempDirectory";
        string sFile = "";

        //create a temporary directory to store selected excel and csv files
        if (!Directory.Exists(tempfolder))
        {
            Directory.CreateDirectory(tempfolder);
        }       
        try
        {
            for (int i = 0; i < listBoxSourceFiles.Items.Count; i++)
            {
                sFile = listBoxSourceFiles.Items[i].ToString();
                // Copy each selected xlsx files into the specified Temporary Folder 
                System.IO.File.Copy(textBoxSourceDir.Text + "\\" + sFile, tempfolder + @"\" + System.IO.Path.GetFileName(sFile), true);
                Log("File " + sFile + " has been copied to " + tempfolder + @"\" + System.IO.Path.GetFileName(sFile));                                                                          
            } // ends foreach    

            Process convertFilesProcess = new Process();
            // remove xlsx extension from filename so that we can add the .csv extension 
            string csvFileName = sourceFileOpenFileDialog.FileName.Substring(0, sourceFileOpenFileDialog.FileName.Length - 3);

            // command prompt execution for converting xlsx files to csv
            convertFilesProcess.StartInfo.WorkingDirectory = "I:\\CommissisionReconciliation\\App\\ConvertExcel\\";
            convertFilesProcess.StartInfo.FileName = "ConvertExcelTo.exe";
            convertFilesProcess.StartInfo.Arguments = " ^ " + targetFolderBrowserDialog.SelectedPath + "^" + csvFileName + ".csv";
            convertFilesProcess.StartInfo.UseShellExecute = true;
            convertFilesProcess.StartInfo.CreateNoWindow = true;
            convertFilesProcess.StartInfo.RedirectStandardOutput = true;
            convertFilesProcess.StartInfo.RedirectStandardError = true;
            convertFilesProcess.Start();

            //Process that creates all the xlsx files in temp folder to csv files.
            Process consolidateFilesProcess = new Process();

            // command prompt execution for CSV File Consolidation
            consolidateFilesProcess.StartInfo.WorkingDirectory = targetFolderBrowserDialog.SelectedPath;
            consolidateFilesProcess.StartInfo.Arguments = "Copy *.csv ^" + csvFileName + ".csv";
            consolidateFilesProcess.StartInfo.UseShellExecute = false;
            consolidateFilesProcess.StartInfo.CreateNoWindow = true;
            consolidateFilesProcess.StartInfo.RedirectStandardOutput = true;
            consolidateFilesProcess.StartInfo.RedirectStandardError = true;
            consolidateFilesProcess.Start();

            Log("All Files at " + tempfolder + " has been converted to a csv file");
            Thread.Sleep(2000);
            StreamReader sOut = consolidateFilesProcess.StandardOutput;
            sOut.Close();

        }
        catch (SecurityException ex)
        {
            // The user lacks appropriate permissions to read files, discover paths, etc.
            MessageBox.Show("Security error. The user lacks appropriate permissions to read files, discover paths, etc. Please contact your administrator for details.\n\n" +
            "Error message: " + ex.Message + "\n\n");
        }
        catch (Exception ex)
        {
            // Could not load the image - probably related to Windows file system permissions.
            MessageBox.Show("You may not have permission to read the file, or " +
             "it may be corrupt.\n\nReported error: " + ex.Message);
        }
        try
        {                
            if (Directory.Exists(tempfolder))
            {
                Directory.Delete(tempfolder, true);
            }
        }
        catch (SecurityException ex)
        {
            // The user lacks appropriate permissions to read files, discover paths, etc.
            MessageBox.Show("Security error. The user lacks appropriate permissions to read files, discover paths, etc. Please contact your administrator for details.\n\n" +
            "Error message: " + ex.Message + "\n\n");
        }
        catch (Exception ex)
        {
            // Could not load the image - probably related to Windows file system permissions.
            MessageBox.Show("You may not have permission to read the file, or " +
             "it may be corrupt.\n\nReported error: " + ex.Message);
        }
        finally
        {
            // reset events
            m_EventStopThread.Reset();
            m_EventThreadStopped.Reset();

            // create worker thread instance;
            m_WorkerThread = new Thread(new ThreadStart(this.WorkerThreadFunction));
            m_WorkerThread.Start();
        }
    } // ends void ExecuteConsolidate()

感谢您的期待! :) 所有有用的答案都将获得投票! :) 如果您需要更多信息,例如workerThread方法或app.config代码,请告诉我们!

3 个答案:

答案 0 :(得分:3)

这条线最有可能导致您的问题:

string csvFileName = sourceFileOpenFileDialog.FileName.Substring(0, sourceFileOpenFileDialog.FileName.Length - 3);

为什么不使用Path.GetFileNameWithoutExtension来获取没有扩展名的文件名?

答案 1 :(得分:2)

我想它会死在这里:

string csvFileName = sourceFileOpenFileDialog.FileName.Substring(0, 
           sourceFileOpenFileDialog.FileName.Length - 3);

像这样写,看它是否有帮助:

string selectedFile = sourceFileOpenFileDialog.FileName;
string csvFileName = Path.Combine(Path.GetDirectoryName(selectedFile), 
           Path.GetFileNameWithoutExtension(selectedFile));

这是你的专栏的翻译。

但我想,你真的想要没有路径的文件名:

string csvFileName = 
         Path.GetFileNameWithoutExtension(sourceFileOpenFileDialog.FileName);

答案 2 :(得分:1)

打破所有错误:

  • 转到“调试” - &gt;例外(或CTRL + ALT + E)

  • 在公共语言运行时异常上勾选“Thrown”

  • 完成修复后,别忘了重置它(全部重设按钮)