我想从DataGridView导出到文本文件,但我得到以下错误:我想从DataGridView导出到文本文件,但我得到的错误
An unhandled exception of type 'System.Security.SecurityException'
occurred in mscorlib.dll
Additional information: Request for the permission of type
'System.Security.Permissions.FileIOPermission, mscorlib,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
这是我的代码:
const string path = @"d:\export.txt";
if (!File.Exists(path))
{
File.Create(path);
}
TextWriter sw = new StreamWriter(@"d:\export.txt");
int rowcount = dgvSum.Rows.Count;
for (int i = 0; i < rowcount - 1; i++)
{
sw.WriteLine(dgvSum.Rows[i].Cells[0].Value.ToString());
}
sw.Close();
MessageBox.Show(@"Text file was created.");
这是我的try-catch报告: this is my report for try-catch:
this is report after changeing path and filename
这个ID确切一些代码编辑后: 尝试 {
const string path = @"c:\123\123.txt";
using (FileStream fileStream = File.Open(path,
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
using (TextWriter sw = new StreamWriter(fileStream))
{
int rowcount = dgvSum.Rows.Count;
for (int i = 0; i < rowcount - 1; i++)
{
sw.WriteLine(dgvSum.Rows[i].Cells[0].Value.ToString());
}
}
MessageBox.Show(@"Text file was created.");
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
//Console.WriteLine(exception);
}
如果你包裹在你的代码中的'试穿catch'阻止你应该看到这个问题是有关该文件的权限。 –
那我该如何解决这个问题? – Hooman
您需要检查您是否有权写入D:驱动器。 –