0

我想从 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 报告: 这是我的 try-catch 报告:

这是更改路径和文件名后的报告

code经过一些编辑后,此 ID 完全一致:

try
{
    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);
}
4

4 回答 4

1

System.Security.SecurityException在您的方法调用中的原因File.Create。它创建文件并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.");
于 2016-06-07T10:48:04.523 回答
0
  1. 右键单击文件“export.txt”-> 属性-> 安全确保您的用户具有写入权限。
  2. 在 using 语句中使用流,例如

    using (var fileStream = new FileStream(file, FileMode.Open))
    {
         using (var textReader = new StreamReader(fileStream))
         {
         }
     }
    
于 2016-06-07T11:32:05.303 回答
0

试试这个代码

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) { } 
于 2016-06-07T11:04:25.137 回答
-1

在配置文件中添加它,我认为这对你有用

于 2016-06-07T10:41:24.467 回答