繁体   English   中英

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

[英]C# WebClient.UploadFileAsync Cannot access the file because it's being used by another process

我正在构建一个简单的应用程序,它将计算机上的文件夹与远程服务器同步。 我使用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");
        }
    }

FileManager.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);
    }

谢谢您的帮助 ! :)

它不会让您上传文件,因为已经使用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);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM