【问题标题】:Appending text to network hosted file将文本附加到网络托管文件
【发布时间】:2014-11-05 13:42:03
【问题描述】:

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

System.UnauthorizedAccessException:对路径的访问被拒绝。

我最初可以创建文件,如果我删除它,我可以重新创建它,如果我在没有“附加”标签的情况下运行我的代码,我可以覆盖该文件,所以我知道拒绝访问消息不是权限问题.

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

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

【问题讨论】:

  • 是否有可能另一个进程正在同时对其进行写入,或者锁定了它?
  • 您有不止一个人在写入文件。这不受支持。您应该只安装 Sql Express 并将您的日志写入网络可用的实例。
  • 我认为其他任何东西都不可能在使用该文件。此时只有我在使用该实用程序。如果我在实用程序之外手动编辑文件,则附加和保存没有问题。如果我让文件保持打开状态然后运行我的实用程序,我会收到一条有意义的不同消息:无法访问该文件,因为它正在被另一个进程使用。
  • UnauthorizedAccessException = 当操作系统因 I/O 错误或特定类型的安全错误而拒绝访问时引发的异常。
  • 我更改了网络共享路径以避免发布公司数据。真实路径是 100% 有效的,并且显然可以使用,因为我能够使用这行代码创建文件。

标签: c# networking text append unc


【解决方案1】:

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

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    相关资源
    最近更新 更多