使用Backgroundworker复制时出现文件使用错误

时间:2019-06-19 15:30:52

标签: c# file backgroundworker

我正在使用这个gist example的后台工作人员来复制文件 并且在DoWork函数上得到文件正在被另一个进程使用的错误:

  

System.IO.IOException:'进程无法访问文件   'C:\ VisualStudio \ MyApp \ bin \最新\资产\内容\ colours_of_a_rainbow_2.png'   因为它正在被另一个进程使用。'

发生这种情况的代码是这样的:

    private void DoWork(object sender, DoWorkEventArgs e)
    {
        int bufferSize = 1024*512;
        using(FileStream inStream = new FileStream(_source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (FileStream fileStream = new FileStream(_target, FileMode.OpenOrCreate, FileAccess.Write))
        {
            int bytesRead = -1;
            var totalReads = 0;
            var totalBytes = inStream.Length;
            byte[] bytes = new byte[bufferSize];
            int prevPercent = 0;

            while ((bytesRead = inStream.Read(bytes, 0, bufferSize)) > 0)
            {
                fileStream.Write(bytes, 0, bytesRead);
                totalReads += bytesRead;
                int  percent = System.Convert.ToInt32(((decimal)totalReads / (decimal)totalBytes) * 100);
                if (percent != prevPercent)
                {
                    _worker.ReportProgress(percent);
                    prevPercent = percent;
                }
            }
        }
    }

如果能在此问题上获得帮助,我将不胜感激。

1 个答案:

答案 0 :(得分:-1)

我认为,如果您特别在第一个using语句中重写代码,使其包含第二个using语句,则可以解决该问题。尽管我没有要测试的C#编译器,但它应该能够像下面那样工作。

private void DoWork(object sender, DoWorkEventArgs e)
{
    int bufferSize = 1024*512;
    using(FileStream inStream = new FileStream(_source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        using (FileStream fileStream = new FileStream(_target, FileMode.OpenOrCreate, FileAccess.Write))
        {
            int bytesRead = -1;
            var totalReads = 0;
            var totalBytes = inStream.Length;
            byte[] bytes = new byte[bufferSize];
            int prevPercent = 0;

            while ((bytesRead = inStream.Read(bytes, 0, bufferSize)) > 0)
            {
                fileStream.Write(bytes, 0, bytesRead);
                totalReads += bytesRead;
                int  percent = System.Convert.ToInt32(((decimal)totalReads / (decimal)totalBytes) * 100);
                if (percent != prevPercent)
                {
                    _worker.ReportProgress(percent);
                    prevPercent = percent;
                }
            }
        }
    }
}