我想从datagridview导出到文本文件,但我得到了以下error
:
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.
这是我的code
:
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的报告:这是我的试抓报告:
这是更改路径和文件名后的报告
经过一些编辑后,此id精确为code
:
try
{
const string path = @"c:123123.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);
}
调用File.Create
方法时出现System.Security.SecurityException
的原因。它创建文件并在创建的文件上打开FileStream
。您没有关闭由File.Create
流打开的,因此StreamWriter
无法打开第二个流。
将代码更改为以下内容:
const string path = @"d:export.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.");
试试这个代码
try
{
string filepath = @"d:export.txt"
using (TextWriter stream = File.Exists(filepath) ? new StreamWriter(filepath) : new StreamWriter(File.Create(filepath)))
{
int rowcount = dgvSum.Rows.Count;
for(int i = 0; i < rowcount - 1; i++)
{
stream.WriteLine(dgvSum.Rows[i].Cells[0].Value.ToString());
}
}
}
catch (Exception) { }
- 右键单击文件"export.txt"->属性->安全性确保您的用户具有写入权限
-
使用类似的语句在内部使用流
using (var fileStream = new FileStream(file, FileMode.Open)) { using (var textReader = new StreamReader(fileStream)) { } }
将其添加到配置文件中,我认为这将适用于您