如何使用C#在winforms中复制文件 [英] how to copy file in winforms with C#

查看:72
本文介绍了如何使用C#在winforms中复制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码复制图像... 
但是当更新图像时,我想先删除此图像,然后复制新图像...这是工作好吧...

但是当表单关闭并再次打开表单时,它会显示错误:它正被另一个进程使用。那我怎么能解决这个错误呢。





 使用(DataTableAdapters.FilePathTableAdapter Path =  new   global  :: SmartEducationSystem.DataTableAdapters。 FilePathTableAdapter())
{
DataTable dt1 = Path.FilePath_GetDataByName( Photo Path);
if (dt.Rows.Count > 0
{
string P_Path = dt1.Rows [ 0 ] [ Path]。ToString()+ Logo.jpg;

try
{
System.IO.File.Delete(P_Path);
System.IO.File.Copy(PhotoPath + @ \ + filename, P_Path, true );
}
catch (UnauthorizedAccessException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}

imgpath = P_Path;
}
}









< pre lang =text>它被另一个进程使用...

解决方案

这不是你的主要问题;你的主要问题是理解。 表单的概念与UI有关。 UI如何与文件/流操作相关联?您需要接受关注点分离



现在,让我们来解决文件访问问题。



取决于打开文件的方式。最有可能的是,你忘了处理某些事情。处理机制通常会在您的代码的某些执行点上处理您需要以受控方式(与垃圾收集器功能相比)进行清理的某些事项;它的一些典型用途是清理非托管资源 - 这真是一个惊喜! - 关闭文件句柄。



基本上,你需要注意使用任何实现 System.IDisposable 并在适当的点调用 System.IDisposable.Dispose 。请参阅:

http://msdn.microsoft.com/en -us / library / system.idisposable.aspx [ ^ ]。



通过try-finally语句确保即使抛出异常也能完成此调用。最好的万无一失的方法是使用使用语句(不要与使用子句混淆!)。请参阅:

http://msdn.microsoft.com/en-us /library/yh598w02.aspx [ ^ ]。



让我们考虑一个简单的例子。当您使用 System.IO.StreamReader 打开文件时,您可以使用专用模式(这是最好的事情)。在阅读器的实例被处理之前,您将无法并行读取同一文件:



  //  您可以在下一行之前访问文件fileName  
使用(System.IO.StreamReader reader = new System.IO.StreamReader(fileName)){
// 从此刻起,文件访问被阻止;你只能用这个阅读器阅读
string line = reader.ReadLine();
// ...
} // reader.Dispose在此处自动调用
// < span class =code-comment>在这里你可以访问文件





您可以使用不同的方式访问你的文件,你可以获得读,写,读/写访问,在较低级别的文件或流接口等工作,但原则是相同的。



你在哪里有这个问题?这很容易调查。



首先,类似的问题在这里被多次询问,根据我的经验,我知道:在大多数情况下,阻止过程就是你自己的过程。您可能忘记在同一个应用程序中处理/关闭某些内容。所以,首先,检查一下,如上所述。



在某些情况下,你真的需要调查哪个进程拥有哪个文件。为此,我建议使用 Sysinternals Suite 中的一个实用程序。这组实用程序(以前来自 Winternals 公司,目前在Microsoft)是必须的对于任何开发人员,请参阅:

http://technet.microsoft.com/en -us / sysinternals / bb842062 [ ^ ],

http://technet.microsoft.com/en-us/sysinternals / bb545027 [ ^ ]。



您需要的实用程序是 handle.exe ,请参阅:

http://technet.microsoft.com/en-us/sysinternals/bb896655 [ ^ ]。



在您的情况下,您使用文件名参数:

 handle.exe< file_name> 





此实用程序将扫描所有类型的句柄,而不仅仅是文件句柄。对于文件,它将扫描与文件名匹配的所有文件句柄(因此它不必是完整路径名)并返回足以识别每个进程的信息,包括其 pid 。因此,如果您需要有关相关流程的更多信息,您还可以使用其他Sysinternals实用程序,特别是其 Process Explorer

http://technet.microsoft.com/en-us/sysinternals/bb896653 [ ^ ]。



祝你好运,

-SA


Im using this code to copy the image...
but when update the image, i want to first delete this image, then copy new image... it is work well...

but when form is close and again open the form then it is display the Error like : it is being use by another process. so how can i solve this error.



using (DataTableAdapters.FilePathTableAdapter Path = new global::SmartEducationSystem.DataTableAdapters.FilePathTableAdapter())
                                {
                                    DataTable dt1 = Path.FilePath_GetDataByName("Photo Path");
                                    if (dt.Rows.Count > 0)
                                    {
                                        string P_Path = dt1.Rows[0]["Path"].ToString() + "Logo.jpg";

                                        try
                                        {
                                            System.IO.File.Delete(P_Path);
                                            System.IO.File.Copy(PhotoPath + @"\" + filename, P_Path, true);
                                        }
                                        catch (UnauthorizedAccessException dirNotFound)
                                        {
                                            Console.WriteLine(dirNotFound.Message);
                                        }

                                        imgpath = P_Path;
                                    }
                                }





it is being used by another process...

解决方案

This is not your main problem; you main problem is understanding. The notion of "Form" is related to UI. How a UI can be related to such thing as file/stream operations? You need to embrace separation of concerns.

Now, let's get to the problem of the file access.

It depends on how you opened the file. Most likely, you forgot to dispose something. The disposal mechanism usually takes care of certain things you need to clean up in a controlled manner (in contrast to, say, Garbage Collector functionality), in some point of execution of your code; and some typical uses of it are cleaning up unmanaged resources and — what a surprise! — closing of file handles.

Basically, you need to watch yourself of using of any types implementing System.IDisposable and call System.IDisposable.Dispose in the appropriate points. Please see:
http://msdn.microsoft.com/en-us/library/system.idisposable.aspx[^].

It's important to makes sure this call is done even if exception is thrown, via a try-finally statement. The best fool-proof way of doing it is using the using statement (don't mix it up with using clause!). Please see:
http://msdn.microsoft.com/en-us/library/yh598w02.aspx[^].

Let's consider a simple example. When you open a file with System.IO.StreamReader, you do it in the exclusive-use mode (which is the best thing to do anyway). You won't be able to read the same file in parallel until the instance of the reader is disposed:

// you can access the file fileName before the next line
using (System.IO.StreamReader reader = new System.IO.StreamReader(fileName)) {
    // from this moment, file access is blocked; you can only read it with this reader
    string line = reader.ReadLine();
    //...
} //reader.Dispose is called here automatically
// and here you can access the file



You could have used different ways of accessing your files, you could get read, write, read/write access, work on lower levels of file or stream interfaces, etc., but the principle is the same.

Where do you have this problem? This is easy to investigate.

First of all, the similar question was asked here many times, and from this experience I know: in most cases the blocking process is your own process. You could have forgotten to dispose/close something in the same application. So, first of all, check it up, as explained above.

In some cases, you really need to investigate which process holds which file. For this, I recommend using one utility from the Sysinternals Suite. This set of utilities (formerly from Winternals company, presently at Microsoft) is a must-have for any developer, please see:
http://technet.microsoft.com/en-us/sysinternals/bb842062[^],
http://technet.microsoft.com/en-us/sysinternals/bb545027[^].

The utility you need is "handle.exe", please see:
http://technet.microsoft.com/en-us/sysinternals/bb896655[^].

In your case, you use it with file name parameter:

handle.exe <file_name>



This utility will scan all kinds of handles, not just file handles. For file, it will scan all file handles matching the file name (so it does not have to be a full path name) and return information sufficient to identify each process, including its pid. So, if you need more information on a process in question, you can also use other Sysinternals utilities, in particular, its Process Explorer:
http://technet.microsoft.com/en-us/sysinternals/bb896653[^].

Good luck,

—SA


这篇关于如何使用C#在winforms中复制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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