检查共享网络驱动器上的文件是否可访问
我有一个程序可以执行不同的操作,我的问题与访问网络映射驱动器或共享文件夹中的文件有关,
该程序可以从网络(网络映射驱动器或共享文件夹)运行文件 msi/exe 该程序可以从网络(网络映射驱动器或共享文件夹)复制文件,
在尝试运行或复制之前如何检查文件是否可访问(如果网络断开或任何其他网络问题)?
File.Exists();
就足够了,
这是我的代码示例:
public static bool FileIsOk(string path)
{
try
{
FileInfo finfo = new FileInfo(path);
if (finfo.Exists)
{
return true;
}
MessageBox.Show("file does not exist, or there is a problem with the network preventing access to the file!");
return false;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return false;
}
谢谢
I have a program that does different things my questions is related to access files in a network mapped drive or a shared folder
the program can run a file msi/exe from the network (network mapped drive or a shared folder)
the program can copy file from the network (network mapped drive or a shared folder)
how I can check if the files are accessible before I try to run or copy (in case of a network disconnection, or any other network problem)?
is it enough with File.Exists();
here is an example of my code:
public static bool FileIsOk(string path)
{
try
{
FileInfo finfo = new FileInfo(path);
if (finfo.Exists)
{
return true;
}
MessageBox.Show("file does not exist, or there is a problem with the network preventing access to the file!");
return false;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return false;
}
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
File.Exists() 应该没问题,但如果您启动大型复制操作,如果在此过程中连接断开,您将无能为力,因此您需要确保为此编写代码。
您应该捕获 IOException 并按照您认为合适的方式处理它。
编辑:捕获 IOException 的代码:
File.Exists() should be fine, but if you start a large copy operation, there's not a lot you can do if the connection goes down during that process, so you'll want to make sure you code for that.
You should trap the
IOException
and handle it as you see fit.EDIT: code to trap IOException:
不。只需尝试操作即可。它会同样快地失败,并且您不会引入时间窗口问题。无论如何你都必须应对这种失败,为什么要编码两次呢?
Don't. Just attempt the operation. It will fail just as fast, and you won't be introducing a timing window problem. You have to cope with that failure anyway, why code it twice?
当然,最好的想法是创建设置的本地缓存。您不能信任网络连接。它们在运行过程中可能会减慢或损坏。如果一切都通过网络运行,我想说,这绝对不是一个安全的想法。
但就技术问题而言,文件存在应该没问题。已经讨论了一个更具描述性的想法来检查文件是否存在。 阅读此处。
The best idea, of course, would be to create local cache of the setup. You cannot trust network connections. They may slow down or break during operation. If everything is run from network, I would say, it's definitely not a safe idea.
But as far as technical question is concerned, File Exists should be fine. A much more descriptive idea has already been discussed to check the existence of a file. Read here.