C# - WinForms 应用程序上的 StreamReader SecurityException 处理 OpenFileDialog 相关错误
大家好,背景: 我正在使用 C# 和 OpenFileDialog、FileBrowserDialog 开发一个 WinForms 应用程序,它将使用命令行可执行文件将多个文件从 excel 转换为 1 个 csv 文件。
错误:我应该添加什么 using 指令或程序集引用来防止这些错误?
- “sOut”在当前上下文中不存在
- “sErr”在当前上下文中不存在
- “sourceFileOpenFileDialog.SelectedFiles”不包含'SelectedFiles' 的定义,并且找不到接受 system.windows.forms.openfiledialog 类型的第一个参数的扩展方法(您是否缺少 using 指令或程序集引用?)
- 'sourceFileOpenFileDialog.SelectedPath' 确实如此不包含“SelectedPath”的定义,并且找不到接受 system.windows.forms.openfiledialog 类型的第一个参数的扩展方法(您是否缺少 using 指令或程序集引用?)
- “SecurityException”无法找到(是否缺少 using 指令或程序集引用?)
- 无法找到“Process”(是否缺少 using 指令或程序集引用?)
- “fileName' 无法找到(是否缺少 using 指令或程序集引用?)
- 'sourceFileOpenFileDialog.FileNames' 无法将类型 'string[]' 隐式转换为 'string'
谢谢!
以下是 MainForm.CS 文件中的代码:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Diagnostics;
using System.Security;
// 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 convertFilesProcess = new Process();
// command prompt execution
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();
StreamReader sOut = convertFilesProcess.StandardOutput;
StreamReader sErr = convertFilesProcess.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
{
Stream 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 = "ConvertExcelTo.exe";
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)
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;
} // ends selectFilesButton_Click method
// Source Folder Path Click Button
Hey Everyone, Background:
I'm developing a WinForms application using C# with an OpenFileDialog, FileBrowserDialog that will convert multiple files from excel to 1 csv file using a command line executable.
Errors: What using directives or assembly references should I add to prevent these errors??
- 'sOut' does not exist in the current context
- 'sErr' does not exist in the current context
- 'sourceFileOpenFileDialog.SelectedFiles' does not contain a definition for 'SelectedFiles' and no extension method accepting a first arg of type system.windows.forms.openfiledialog could be found (are you missing a using directive or assembly reference?)
- 'sourceFileOpenFileDialog.SelectedPath' does not contain a definition for 'SelectedPath' and no extension method accepting a first arg of type system.windows.forms.openfiledialog could be found (are you missing a using directive or assembly reference?)
- 'SecurityException' could not be found (are you missing a using directive or assembly reference?)
- 'Process' could not be found (are you missing a using directive or assembly reference?)
- 'fileName' could not be found (are you missing a using directive or assembly reference?)
- 'sourceFileOpenFileDialog.FileNames' cannot implicitly convert type 'string[]' to 'string'
Thanks!
Here's the code from the MainForm.CS file:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Diagnostics;
using System.Security;
// 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 convertFilesProcess = new Process();
// command prompt execution
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();
StreamReader sOut = convertFilesProcess.StandardOutput;
StreamReader sErr = convertFilesProcess.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
{
Stream 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 = "ConvertExcelTo.exe";
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)
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;
} // ends selectFilesButton_Click method
// Source Folder Path Click Button
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要解决您的错误
sourceFileOpenFileDialog.FileNames 无法隐式地将类型 'string[]' 转换为 'string'
您需要更改此部分,您正在尝试将字符串数组推入字符串 (.Text )
也许迭代 FileNames 数组并将字符串连接在一起以放入 .Text 中?
对于“.SelectedFiles”和“.SelectedPath”的问题,这些不是 openFileDialog 的属性,所以这就是它抱怨的原因。
您可以再次使用“.FileNames”来获取在对话框中选择的文件(或“.FileName”,如果您只允许一项选择)
使用 sOut 和 sErr,您可以在流程后期设置它们,并在最后的语句中清理它们,什么可能发生的情况是,如果进程在你到达你的
行之前爆炸,那么当你点击最后时,它不知道要关闭的 sOut 和 sErr 是什么,因为它们尚未制作。
To solve your error
sourceFileOpenFileDialog.FileNames cannot implicitly convert type 'string[]' to 'string'
You need to change up this section, you're trying to push a string array into a string (.Text)
Maybe iterate through the FileNames array and concatenate the strings together to put into .Text?
For the issues with ".SelectedFiles" and ".SelectedPath", those are not properties of an openFileDialog, so thats why it is complaining..
Again you can use ".FileNames" to get at the files that were selected in the dialog(or ".FileName" if you are allowing only one selection)
With sOut and sErr you are setting them up late in your process and cleaning them up in your finally statement, what may be happening is if the process bombs before you get to your
lines then when you hit the finally, it doesn't know what sOut and sErr to close are, since they were never made yet.
到目前为止已修复以下错误:
,无法找到
'SecurityException'(您是否缺少 using 指令或程序集引用?)
'Process' 无法 找不到(您是否缺少 using 指令或程序集引用?),方法是添加:
'fileName'通过更改为 sourceFileOpenFileDialog.FileName 无法找到(您是否缺少 using 指令或程序集引用?)
'sourceFileOpenFileDialog.FileNames ' 无法通过更改为 sourceFileOpenFileDialog.FileName 将类型 'string[]' 隐式转换为 'string'
'sOut'&通过更改关闭语句的位置,当前上下文中不存在“sErr”,如下所示。我不确定这是否会扰乱异常捕获器,但我们会看到:
'sourceFileOpenFileDialog.SelectedFiles'不包含'SelectedFiles'的定义,并且没有扩展方法接受第一个可以找到 system.windows.forms.openfiledialog 类型的 arg(您是否缺少 using 指令或程序集引用?)。通过将 SelectedFiles 更改为 FileNames 来修复:
“sourceFileOpenFileDialog.SelectedPath”不包含“SelectedPath”的定义,并且找不到接受 system.windows.forms.openfiledialog 类型的第一个参数的扩展方法(您是否缺少 using 指令或程序集)参考?)。通过将 SelectedPath 更改为 FileName 来修复:
Fixed the following Errors so far:
'SecurityException' could not be found (are you missing a using directive or assembly reference?) by adding
'Process' could not be found (are you missing a using directive or assembly reference?) by adding:
'fileName' could not be found (are you missing a using directive or assembly reference?) by changing to sourceFileOpenFileDialog.FileName
'sourceFileOpenFileDialog.FileNames' cannot implicitly convert type 'string[]' to 'string' by changing to sourceFileOpenFileDialog.FileName
'sOut' & 'sErr' does not exist in the current context fixed by changing placement of the close statements as follows. I'm not sure if this messes up the exception catcher or not but we will see:
'sourceFileOpenFileDialog.SelectedFiles' does not contain a definition for 'SelectedFiles' and no extension method accepting a first arg of type system.windows.forms.openfiledialog could be found (are you missing a using directive or assembly reference?). Fixed by changing SelectedFiles to FileNames:
'sourceFileOpenFileDialog.SelectedPath' does not contain a definition for 'SelectedPath' and no extension method accepting a first arg of type system.windows.forms.openfiledialog could be found (are you missing a using directive or assembly reference?). Fixed by changing SelectedPath to FileName: