StreamWriter具有UnauthorizedAccessException的权限不足

时间:2014-06-22 06:29:10

标签: c# exception streamwriter

我使用以下代码将文件写入桌面。

string submittedFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
int i = 0;
StreamWriter sw = null;
sw = new StreamWriter(submittedFilePath, false);

for (i = 0; i < PSOLib.table.Columns.Count - 1; i++)
{
    sw.Write(PSOLib.table.Columns[i].ColumnName + ";");
}

sw.Write(PSOLib.table.Columns[i].ColumnName);
sw.WriteLine();

foreach (DataRow row in PSOLib.table.Rows)
{
    object[] array = row.ItemArray;

    for (i = 0; i < array.Length - 1; i++)
    {
        sw.Write(array[i].ToString() + ";");
    }

    sw.Write(array[i].ToString());
    sw.WriteLine();
}

sw.Close();

但是每当我尝试调用我得到的方法时:

Access to the path 'C:\\Users\\User\\Desktop' is denied. 
System.UnauthorizedAccessException.

1 个答案:

答案 0 :(得分:3)

您没有为StreamWriter指定文件,而是指定文件夹。

这应该这样做:

string submittedFilePath = 
Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\myFile.txt.";