我想从datagridview导出到文本文件,但我得到错误

时间:2016-06-07 10:24:46

标签: c# datagridview export-to-text

我想从datagridview导出到文本文件,但我得到了RewriteEngine on RewriteCond %{HTTP_HOST} ^(www.)?exemple.com$ RewriteCond %{REQUEST_URI} !^/subfolder1/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /subfolder1/$1 RewriteCond %{HTTP_HOST} ^(www.)?exemple.com$ RewriteRule ^(/)?$ subfolder1/index.php [L]

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

这是我的try-catch报告: this is my report for try-catch:

this is report after changeing path and filename

经过一些编辑后,此ID确切为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.");

code

4 个答案:

答案 0 :(得分: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.");

答案 1 :(得分: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) { } 

答案 2 :(得分:0)

  1. 右键点击文件“export.txt” - &gt;属性 - &gt;安全性确保您的用户具有写入权限。
  2. 使用像

    这样的语句内部的流
    using (var fileStream = new FileStream(file, FileMode.Open))
    {
         using (var textReader = new StreamReader(fileStream))
         {
         }
     }
    

答案 3 :(得分:-1)

在配置文件中添加此内容,我认为这对您有用