【问题标题】:SystemIO: The process cannot access the file X because it is used by another process (same process)SystemIO:该进程无法访问文件X,因为它被另一个进程(同一进程)使用
【发布时间】:2020-04-26 13:57:28
【问题描述】:

我收到了错误 The process cannot access the file X because it is used by another process,我很确定这是同一个过程,因为我检查了所有其他打开的应用程序。

这些是我使用这个文件的时间。

...
string jsonString;
jsonString = JsonSerializer.Serialize(hardware);
System.IO.File.WriteAllText(Directory.GetCurrentDirectory().ToString() + @"\HardwareInfo.json", jsonString);
// ^^ This is where I get the exception ^^
...
...
var uploadFile = path + @"\HardwareInfo.json";
    using (var localStream = File.OpenRead(uploadFile))
    {
        await client.UploadAsync(localStream, Path.GetFileName(uploadFile));
    }
...

我不知道这是否重要,但它在第二种方法中被异步使用。

提前致谢。

【问题讨论】:

  • client 是什么类型?在我看来,当您致电 UploadAsync 时,您正试图再次读取该文件。
  • var client = new SftpClient(host, int.Parse(port), username, password); 这是一个 SftpClient 实例(SshNet)

标签: c# file asynchronous io


【解决方案1】:

无锁编辑:

     using (var memStream = new MemoryStream) 
     {
        using (var localStream = File.OpenRead(uploadFile))
        {
            localStream.CopyTo(memStream);
        }

        await client.UploadAsync(memStream, Path.GetFileName(uploadFile));
     }

【讨论】:

  • cannot await in the body of a lock statement 我无法使 client.UploadAsync 异步。
  • @WoJo 编辑:问题主要是因为您在文件句柄打开时上传。
  • @Mertuarez 这行得通,但是 SFTP 服务器上的文件是空的,我电脑上的文件也不是空的。
  • 这不是防弹的。因此,请指望您的应用程序将开始消耗更多内存,并且在多次读写的情况下会发生冲突。不错的选择是使用线程安全的读写方法创建服务类。 johandorper.com/log/thread-safe-file-writing-csharpdocs.microsoft.com/en-us/dotnet/api/…
猜你喜欢
  • 1970-01-01
  • 2010-12-10
相关资源
最近更新 更多