我想从datagridview导出到文本文件,但出现错误 [英] I want to get export from datagridview to text file but I get error

查看:131
本文介绍了我想从datagridview导出到文本文件,但出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从datagridview导出到文本文件,但是我得到了error:

I want to get export from datagridview to text file but i get following 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的报告: 这是我的尝试捕获报告:

this is my report for try-catch : this is my report for try-catch:

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

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

This id exact code after some edit :

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);
}

推荐答案

调用File.Create方法时System.Security.SecurityException的原因.它创建文件并在创建的文件上打开FileStream.您没有关闭File.Create流打开的文件,因此StreamWriter无法打开第二个文件.

The reason of System.Security.SecurityException in your call of File.Create method. It creates file and opens FileStream on created file. You did not close opened by File.Create stream so StreamWriter can not open a second one.

将代码更改为以下内容:

Change code to following:

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.");

这篇关于我想从datagridview导出到文本文件,但出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆