【问题标题】:C# - Running / Executing "Excel to CSV File Converter" Console App from C# WinForm AppC# - 从 C# WinForm 应用程序运行/执行“Excel 到 CSV 文件转换器”控制台应用程序
【发布时间】:2011-07-18 11:39:33
【问题描述】:

我正在使用带有 OpenFileDialog、FileBrowserDialog 的 C# 开发一个 WinForms 应用程序,并且我已经启用了我想要的多个 xls 文件的选择:

  1. 将选中的文件复制到Consolidated目录
  2. 通过命令提示符命令 [C:\CommissionRecon\ConvertExcel\ConvertExcelTo.exe ^ xxxxx.xls ^ xxxx.csv] 将选定文件转换为 .csv 文件
  3. 使用命令提示符将所有 .csv 文件合并为 1 个 csv 文件 [.csv 文件位置:复制 *.csv ^ 文件名.csv]

执行此控制台应用程序的正确语法是什么??

请检查下面的代码并推荐一些修复方法。我包含了很多代码,以便您了解全局,但我主要希望您尽可能只查看私有 void sourceFiles_Click 方法。

谢谢!

这是 MainForm.CS 文件中的代码:

    // Select Source Files Button 
    private void sourceFiles_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        this.sourceFileOpenFileDialog.InitialDirectory = "i:\\CommissisionReconciliation\\Review\\";
        this.sourceFileOpenFileDialog.Filter = "Excel Files (*.xls;*.xlsx;)|*.xls;*.xlsx;|All Files (*.*)|*.*";
        this.sourceFileOpenFileDialog.FilterIndex = 2;
        this.sourceFileOpenFileDialog.RestoreDirectory = true;
        this.sourceFileOpenFileDialog.Multiselect = true;
        this.sourceFileOpenFileDialog.Title = "Excel File Browser";

        DialogResult dr = this.sourceFileOpenFileDialog.ShowDialog();
        if (dr == System.Windows.Forms.DialogResult.OK)
        {
            string consolidatedFolder = targetFolderBrowserDialog.SelectedPath; 
            // Read the files
            foreach (String file in sourceFileOpenFileDialog.FileNames)
            {
                try
                {
                    // Copy each selected xlsx files into the specified TargetFolder 

                    System.IO.File.Copy(fileName, consolidatedFolder + @"\" + System.IO.Path.GetFileName(fileName)); 

                    // Convert each selected XLSX File to CSV Using the command prompt
                    // [I:\CommissisionReconciliation\App\ConvertExcel\ConvertExcelTo.exe ^ .XLS file location ^ filename.csv] 
                    // example: ConvertExcelTo.exe ^ I:\CommissisionReconciliation\ Review\_Consolidated\ALH\2011-350-00-600070-
                    // 03-09alh-AMLHS of Florida.xlsx ^ 2011-350-00-600070-03-09alh-AMLHS of Florida.csv

                    Process covertFilesProcess = new Process();

                    covertFilesProcess.StartInfo.WorkingDirectory = "I:\\CommissisionReconciliation\\App\\ConvertExcel\\";
                    covertFilesProcess.StartInfo.FileName = sourceFileOpenFileDialog.FileName; 
                    covertFilesProcess.StartInfo.Arguments = "ConvertExcelTo.exe" + " ^ " + targetFolderBrowserDialog.SelectedPath + "^" + sourceFileOpenFileDialog.FileName + ".csv";
                    covertFilesProcess.StartInfo.UseShellExecute = false;
                    covertFilesProcess.StartInfo.CreateNoWindow = true;
                    covertFilesProcess.StartInfo.RedirectStandardOutput = true;
                    covertFilesProcess.StartInfo.RedirectStandardError = true;
                    covertFilesProcess.Start();

                    StreamReader sOut = covertFilesProcess.StandardOutput;
                    StreamReader sErr = covertFilesProcess.StandardError;

                }

                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("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
                     + ". You may not have permission to read the file, or " +
                     "it may be corrupt.\n\nReported error: " + ex.Message);
                }

                finally
                {
                    sOut.Close();
                    sErr.Close();
                }

                try
                {
                    // Combine all .csv files into 1 csv file using the command prompt
                    // [.csv File location: Copy *.csv ^ filename.csv]
                    // example: [.CSV I:\CommissisionReconciliation\ Review\_Consolidated\ALH\: Copy *.csv 
                    // ^2011-350-00-600070-03-09alh-AMLHS of Florida.csv)

                    Process consolidateFilesProcess = new Process();

                    // substring function to take off the extension from sourceFileOpenFileDialog.FileName
                    // int csvFileName.Length = sourceFileOpenFileDialog.FileName.Length - 3;  

                    consolidateFilesProcess.StartInfo.WorkingDirectory = "I:\\CommissisionReconciliation\\App\\ConvertExcel\\";
                    consolidateFilesProcess.StartInfo.FileName = sourceFileOpenFileDialog.FileName; 
                    consolidateFilesProcess.StartInfo.Arguments = ".CSV " + " ^ " + targetFolderBrowserDialog.SelectedPath + ": Copy *.csv ^" + csvFileName+ ".csv";
                    consolidateFilesProcess.StartInfo.UseShellExecute = false;
                    consolidateFilesProcess.StartInfo.CreateNoWindow = true;
                    consolidateFilesProcess.StartInfo.RedirectStandardOutput = true;
                    consolidateFilesProcess.StartInfo.RedirectStandardError = true;
                    consolidateFilesProcess.Start();

                    StreamReader sOut = consolidateFilesProcess.StandardOutput;
                    StreamReader sErr = consolidateFilesProcess.StandardError;
                }

                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("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
                     + ". You may not have permission to read the file, or " +
                     "it may be corrupt.\n\nReported error: " + ex.Message);
                }

                finally
                {
                    sOut.Close();
                    sErr.Close();
                }

            } // ends foreach (String file in openFileDialog1.FileNames)
        }  // ends if (dr == System.Windows.Forms.DialogResult.OK)
    } // ends selectFilesButton_Click method 

        if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
        {
            try
            {
                if ((myStream = sourceFileOpenFileDialog.OpenFile()) != null)
                {
                    using (myStream)
                    {
                        textBoxSourceFiles.Text = sourceFileOpenFileDialog.FileNames;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }

        if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
        {
            Log("Source Files: " + sourceFileOpenFileDialog.SelectedFiles);
        }
        textBoxSourceFiles.Text = sourceFileOpenFileDialog.SelectedFiles;
    }

【问题讨论】:

  • 您应该将这些代码块重构为单独的方法,以便 foreach 适合单个屏幕,而不是使用 // ends foreach (...)
  • @gaearon,对不起,我不确定你的意思。你能举个例子吗?
  • 在结尾大括号中放置 cmets,指定哪个是左大括号(例如 // ends if (dr == System.Windows.Forms.DialogResult.OK))。这是一种不好的风格,因为它表明您的代码块足够长,以至于它们不适合屏幕。这样的代码很难阅读和维护。如果您将代码的一部分提取到单独的方法中,通常代码看起来会更好。例如,您可以创建一个StartConverter 方法并在循环中调用它。

标签: c# winforms error-handling console-application


【解决方案1】:

创建ProcessSTartInfo时,需要指定要运行的进程的可执行文件名!

例如:

Process covertFilesProcess = new Process();

covertFilesProcess.StartInfo.WorkingDirectory = "I:\\CommissisionReconciliation\\App\\ConvertExcel\\";
covertFilesProcess.StartInfo.FileName = "ConvertExcelTo.exe";
covertFilesProcess.StartInfo.Arguments = "^ " + targetFolderBrowserDialog.SelectedPath + "^" + sourceFileOpenFileDialog.FileName + ".csv";
covertFilesProcess.StartInfo.UseShellExecute = true;
covertFilesProcess.StartInfo.CreateNoWindow = true;
covertFilesProcess.StartInfo.RedirectStandardOutput = true;
covertFilesProcess.StartInfo.RedirectStandardError = true;
covertFilesProcess.Start();

StreamReader sOut = covertFilesProcess.StandardOutput;
StreamReader sErr = covertFilesProcess.StandardError;

【讨论】:

  • 感谢您的回复!我会试试的!我应该添加什么使用指令或程序集引用来防止这些错误?找不到“fileName”(是否缺少 using 指令或程序集引用?)找不到“Process”(是否缺少 using 指令或程序集引用?)找不到“SecurityException”(是否缺少使用指令或程序集引用?)“sOut”在当前上下文中不存在“sErr”在当前上下文中不存在
  • @Frank Hale,感谢您的回复。你在这里的代码中编辑了什么?关于如何修复我的错误,您有什么要补充的吗?
  • string directoryPath = Path.GetDirectoryName(filePath); ?
【解决方案2】:

首先:

try
{
    ...
    StreamReader sOut = covertFilesProcess.StandardOutput;
}
sOut.close();

sOut 在 try 块内声明 - 它在外部不可见。你需要把它移到外面像这样

StreamReader sOut = null;
try
{
    ...
    sOut = covertFilesProcess.StandardOutput;
}

if (sOut != null) sOut.Close();

与 sErr 相同

更新:对于 SecurityException,您需要使用 System.Security 添加,对于 Process,您需要使用 System.Diagnostics 添加。并且变量 fileName 没有被声明——所以编译器不知道它是什么。

【讨论】:

  • 感谢您的回复。在你给我的代码下,我应该在下面放什么而不是“...”:“StreamReader sOut = null; try { ... sOut = ... }”??
  • 我已经在上面的代码中声明了 sOut & sErr 变量如下:“StreamReader sOut = covertFilesProcess.StandardOutput; StreamReader sErr =covertFilesProcess.StandardError;”这就是您对 ... 和 sOut=... 的意思吗?
  • 对于sOut = ...,我想用sOut = covertFilesProcess.StandardOutput 表示分配。我更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-16
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-16
  • 2013-06-10
相关资源
最近更新 更多