c# WebClient.UploadFileAsync无法访问该文件,因为它正在被另一个进程使用

本文关键字:另一个 进程 因为 UploadFileAsync WebClient 访问 文件 | 更新日期: 2023-09-27 18:06:46

我正在构建一个简单的应用程序,用于将计算机上的文件夹与远程服务器同步。我使用FileSystelWatcher来检测更改和WebClient来上传文件。问题是,当我试图上传时,我得到一个异常说文件已经在使用中。我检查了所有的进程,但我找不到阻塞的进程。当多个文件被添加到一个目录时,我也用FileSystemWatcher尝试了这个文件访问错误,但问题仍然相同。下面是我如何声明FileSysemWatcher:

private void InitFileWatcher()
    {
        try
        {
            watcher = new FileSystemWatcher();
            watcher.Path = FileManager.getSyncDirPath();
            watcher.EnableRaisingEvents = true;
            watcher.IncludeSubdirectories = true;
            watcher.Created += FileManager.FileCreated;
        }
        catch(Exception)
        {
            Console.WriteLine("Error");
        }
    }

文件管理。FileCreated方法:

public static void FileCreated(object sender, FileSystemEventArgs e) 
    {
        Console.WriteLine("File created: " + e.FullPath);
        while (true)
        {
            try
            {
                using (Stream stream = System.IO.File.Open(e.FullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    if (stream != null)
                    {
                        FileUploader uploader = new FileUploader();
                        uploader.Upload(e.FullPath, new Uri("http://192.168.65.1/test/upload.php"));
                        break;
                    }
                }
            }
            catch (FileNotFoundException ex)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Output file {0} not yet ready ({1})", e.FullPath, ex.Message));
            }
            catch (IOException ex)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Output file {0} not yet ready ({1})", e.FullPath, ex.Message));
            }
            catch (UnauthorizedAccessException ex)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Output file {0} not yet ready ({1})", e.FullPath, ex.Message));
            }
            Thread.Sleep(500);
        }
    }
最后是上传方法:
public void Upload(string file, Uri destination)
    {
        WebClient client = new WebClient();
        client.Headers.Add("Content-Type", "binary/octet-stream");
        client.UploadFileAsync(destination, "POST", file);
    }

谢谢你的帮助!:)

c# WebClient.UploadFileAsync无法访问该文件,因为它正在被另一个进程使用

不允许上传文件,因为文件已经使用System.IO.File.Open打开了

如果您打开文件只是为了检查它是否存在,那么您可以使用

File.Exists(path);

您必须尝试下面提到的代码。

    public void Upload(string file, Uri destination)
    {
       using (WebClient client=new Webclient())
        {
           client.Headers.Add("Content-Type", "binary/octet-stream");
           client.UploadFileAsync(destination, "POST", file);
        }
    }