将文本附加到网络托管文件

时间:2014-09-11 14:35:55

标签: c# networking text append unc

我编写了一个小实用程序,在其中我希望能够写入网络托管日志文件以确认哪些用户运行了该工具。我可以轻松地从我的实用程序中创建该文件,但如果我尝试添加其他文本,我会遇到:

  

System.UnauthorizedAccessException:拒绝访问路径。

我最初可以创建该文件,如果我删除它,我可以重新创建它,如果我运行我的代码而没有'追加'标签我可以覆盖该文件,因此我知道访问被拒绝的消息不是权限。

以下是我正在使用的代码。

using (StreamWriter sw1 = new StreamWriter(@"\\MyNetworkLocation\MyLogFile.csv",true))
{
   sw1.WriteLine(userName + "," + machineName + "," + 
         (string.Format("{0:dddd dd MMMM yyyy}", dt)));
}

1 个答案:

答案 0 :(得分:1)

如果您不想写入数据库或EventLog进行日志记录,请将代码更改为以下内容并查看是否有帮助

using (Stream fs= new FileStream(@"\\MyNetworkLocation\MyLogFile.csv", FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
   fs.Write(userName + "," + machineName + "," + string.Format("{0:dddd dd MMMM yyyy}", dt));
   fs.Flush();
   fs.Close();
}

FIle.Open Method

  

每个MSDN

Parameters
path
Type: System.String
The file to open.
mode
Type: System.IO.FileMode
A FileMode value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.
access
Type: System.IO.FileAccess
A FileAccess value that specifies the operations that can be performed on the file.
share
Type: System.IO.FileShare
A FileShare value specifying the type of access other threads have to the file.
Return Value
Type: System.IO.FileStream
A FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.