1

我喜欢用它System.IO.File.WriteAllBytes()来保持简单。但似乎,这种方法不能到处使用。在我的本地系统上写它工作正常。

但是,当我System.IO.File.WriteAllBytes()在 Windows 共享上写入时,它会生成一个空文件并失败并出现异常:

System.UnauthorizedAccessException: Access to the path '/var/windowsshare/file.bin' is denied.
---> System.IO.IOException: Permission denied

如果我查看https://github.com/dotnet/runtime/blob/c72b54243ade2e1118ab24476220a2eba6057466/src/libraries/System.IO.FileSystem/src/System/IO/File.cs#L421的源代码, 我发现以下代码有效在引擎盖下:

using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
{
    fs.Write(bytes, 0, bytes.Length);
}

如果我更改代码并使用它FileShare.None来代替FileShare.Read它。所以我有一个解决方法,我必须记住它System.IO.File.WriteAllBytes()不防水(对吗?)。

不幸的是,我的分析以一些相关的问题告终:

那么,如果目标路径是可配置的,那么最佳实践是什么?开发人员必须避免 System.IO.File.WriteAllBytes() 还是系统管理员必须找到另一种方式来挂载共享?FileShare.Read 有什么问题?Windows 是否在 System.IO.File.WriteAllBytes() 正在写入时共享更改权限/锁定?是否有一些安装 Windows 共享的提示?

更新 1

写入所有字节():

// WriteAllBytes() Throws System.UnauthorizedAccessException
System.IO.File.WriteAllBytes("/var/windowsshare/file.bin", bytes);

使用 C# 创建和移动

// Create local and move + optional overwrite works!
var tmp = Path.GetTempFileName(); // local file
System.IO.File.WriteAllBytes(tmp, bytes); // write local
System.IO.File.Move(tmp, "/var/windowsshare/file.bin", true); // optional overwrite

ls:

# ls -l /var/windowsshare/file.bin
-rw-rw-rw-. 1 apache apache 20 Feb  9 11:43 /var/windowsshare/file.bin
# ls -Z /var/windowsshare/file.bin
system_u:object_r:cifs_t:s0 /var/windowsshare/file.bin

山 ...

# mount -l
//1.2.3.4/windowsshare on /var/windowsshare type cifs (rw,relatime,vers=3.1.1,cache=strict,username=luke,domain=dom,uid=48,forceuid,gid=48,forcegid,addr=1.2.3.4,file_mode=0666,dir_mode=0777,soft,nounix,nodfs,nouser_xattr,mapposix,noperm,rsize=4194304,wsize=4194304,bsize=1048576,echo_interval=60,actimeo=1,_netdev)

# stat -f -c %T /var/windowsshare/file.bin
smb2
4

1 回答 1

1

Github 上的以下线程(https://github.com/dotnet/runtime/issues/42790 )帮助了我。nobrl最后,我使用该选项重新安装了我的 CIFS 共享。

在线程中他们也得出了 usingFileShare.None有效的结论,但根本原因似乎是我们使用的 CIFS 服务器不支持字节范围锁。

我不确定这意味着什么,但在我的情况下,不需要多次写入文件,也不应该有两个进程试图写入同一个文件。

于 2021-05-04T00:39:25.713 回答