该进程无法访问该文件,因为它正被另一个进程使用.c# [英] The process cannot access the file because it is being used by another process.c#

查看:40
本文介绍了该进程无法访问该文件,因为它正被另一个进程使用.c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 File.Copy() 函数将一张图像从一个位置复制到另一个位置,但它导致进程无法访问异常,任何人都可以帮助解决下面的代码块.我附上了截图例外.

I am trying to copy one image from one location to another location using File.Copy() function but it gives the process can not access exception,any one can please help on this bellow is the code block.I have attached screenshot for exception.

private void btnUpload_Click(object sender, EventArgs e)
{  
    string SourcePath;
    string RootDrive;
    string DestPath;
    string fileName;
    fileName = "";
        try
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Select Image to Upload";
            ofd.Filter = "Jpg|*.jpg|Jpge|*.jpge|Gif|*.gif";
            ofd.FileName = null;
            if (ofd.ShowDialog() != DialogResult.Cancel)
            {
                fileName = ofd.FileName;

            }
            ofd.Dispose();
            DestPath = Directory.GetCurrentDirectory() + @"\Uploads\PropertyImages\";
                string destFile = System.IO.Path.Combine(DestPath, fileName);

                if (!System.IO.Directory.Exists(DestPath))
                {
                    System.IO.Directory.CreateDirectory(DestPath);
                }
                System.IO.File.Copy(fileName, destFile, true);                                   

        }
        catch (Exception ae)
        {
            MessageBox.Show(ae.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

推荐答案

这可能是因为您试图将文件复制到自身.对 Combine() 的调用,正如您所拥有的,只是返回 fileName.更改以下行:

It's probably because you are attempting to copy the file to itself. The call to Combine(), as you have it, is just returning fileName. Change the following line:

string destFile = System.IO.Path.Combine(DestPath, fileName);

string destFile = System.IO.Path.Combine(DestPath, System.IO.Path.GetFileName(fileName));

这篇关于该进程无法访问该文件,因为它正被另一个进程使用.c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆