在 C# 中验证文件是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/415962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Verify if file exists or not in C#
提问by
I am working on an application. That application should get the resume from the users, so that I need a code to verify whether a file exists or not.
我正在处理一个应用程序。该应用程序应该从用户那里获取简历,因此我需要一个代码来验证文件是否存在。
I'm using ASP.NET / C#.
我正在使用 ASP.NET/C#。
回答by James Ogden
To test whether a file exists in .NET, you can use
要测试文件是否存在于 .NET 中,您可以使用
System.IO.File.Exists (String)
回答by Ruben
You could use:
你可以使用:
System.IO.File.Exists(@"c:\temp\test.txt");
回答by splattne
You can determine whether a specified file exists using the Exists
method of the File
class in the System.IO
namespace:
您可以使用命名空间Exists
中的File
类的方法来确定指定的文件是否存在System.IO
:
bool System.IO.File.Exists(string path)
You can find the documentation here on MSDN.
Example:
例子:
using System;
using System.IO;
class Test
{
public static void Main()
{
string resumeFile = @"c:\ResumesArchive3823.txt";
string newFile = @"c:\ResumesImport\newResume.txt";
if (File.Exists(resumeFile))
{
File.Copy(resumeFile, newFile);
}
else
{
Console.WriteLine("Resume file does not exist.");
}
}
}
回答by erikkallen
In addition to using File.Exists()
, you might be better off just trying to use the file and catching any exception that is thrown. The file can fail to open because of other things than not existing.
除了使用之外File.Exists()
,您最好尝试使用该文件并捕获抛出的任何异常。文件可能会因为不存在以外的其他原因而无法打开。
回答by Todd Friedlich
Can't comment yet, but I just wanted to disagree/clarify with erikkallen.
还不能发表评论,但我只是想不同意/澄清erikkallen。
You should not just catch the exception in the situation you've described. If you KNEW that the file should be there and due to some exceptionalcase, it wasn't, then it would be acceptable to just attempt to access the file and catch any exception that occurs.
您不应该只是在您所描述的情况下捕获异常。如果您知道该文件应该在那里并且由于某些特殊情况而没有,那么尝试访问该文件并捕获发生的任何异常是可以接受的。
In this case, however, you are receiving input from a user and have little reason to believe that the file exists. Here you should always use File.Exists().
但是,在这种情况下,您正在接收来自用户的输入并且没有理由相信该文件存在。在这里,您应该始终使用 File.Exists()。
I know it is cliché, but you should only use Exceptions for an exceptional event, not as part as the normal flow of your application. It is expensive and makes code more difficult to read/follow.
我知道这是陈词滥调,但您应该只将 Exceptions 用于异常事件,而不是作为应用程序正常流程的一部分。它很昂贵并且使代码更难以阅读/遵循。
回答by ZombieSheep
These answers all assume the file you are checking is on the server side. Unfortunately, there is no cast iron way to ensure that a file exists on the client side (e.g. if you are uploading the resume). Sure, you can do it in Javascript but you are still not going to be 100% sure on the server side.
这些答案都假设您正在检查的文件在服务器端。不幸的是,没有铸铁方法来确保文件存在于客户端(例如,如果您正在上传简历)。当然,您可以在 Javascript 中做到这一点,但您仍然不能 100% 确定在服务器端。
The best way to handle this, in my opinion, is to assume that the user will actually select an appropriate file for upload, and then do whatever work you need to do to ensure the uploaded file is what you expect (hint - assume the user is trying to poison your system in every possible way with his/her input)
在我看来,处理这个问题的最好方法是假设用户实际上会选择一个合适的文件进行上传,然后做任何你需要做的工作来确保上传的文件是你所期望的(提示 - 假设用户试图用他/她的输入以各种可能的方式毒害您的系统)
回答by Dror
You wrote asp.net - are you looking to upload a file?
if so you can use the html
你写了asp.net - 你想上传一个文件吗?
如果是这样,您可以使用 html
<input type="file" ...
<输入类型=“文件”...
回答by Keith
Simple answer is that you can't - you won't be able to check a for a file on their machine from an ASP website, as to do so would be a dangerous risk for them.
简单的答案是你不能 - 你将无法从 ASP 网站检查他们机器上的文件,因为这样做对他们来说是一个危险的风险。
You have to give them a file upload control - and there's not much you can do with that control. For security reasons javascript can't really touch it.
你必须给他们一个文件上传控制——而且你不能用这个控制做很多事情。出于安全原因,javascript 无法真正触及它。
<asp:FileUpload ID="FileUpload1" runat="server" />
They then pick a file to upload, and you have to deal with any empty file that they might send up server side.
然后他们选择要上传的文件,您必须处理他们可能发送到服务器端的任何空文件。
回答by Deekshit Kumar
This may help you.
这可能对你有帮助。
try
{
con.Open();
if ((fileUpload1.PostedFile != null) && (fileUpload1.PostedFile.ContentLength > 0))
{
filename = System.IO.Path.GetFileName(fileUpload1.PostedFile.FileName);
ext = System.IO.Path.GetExtension(filename).ToLower();
string str=@"/Resumes/" + filename;
saveloc = (Server.MapPath(".") + str);
string[] exts = { ".doc", ".docx", ".pdf", ".rtf" };
for (int i = 0; i < exts.Length; i++)
{
if (ext == exts[i])
fileok = true;
}
if (fileok)
{
if (File.Exists(saveloc))
throw new Exception(Label1.Text="File exists!!!");
fileUpload1.PostedFile.SaveAs(saveloc);
cmd = new SqlCommand("insert into candidate values('" + candidatename + "','" + candidatemail + "','" + candidatemobile + "','" + filename + "','" + str + "')", con);
cmd.ExecuteNonQuery();
Label1.Text = "Upload Successful!!!";
Label1.ForeColor = System.Drawing.Color.Blue;
con.Close();
}
else
{
Label1.Text = "Upload not successful!!!";
Label1.ForeColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ee) { Label1.Text = ee.Message; }
回答by Eric Bishard
if (File.Exists(Server.MapPath("~/Images/associates/" + Html.DisplayFor(modelItem => item.AssociateImage))))
{
<img src="~/Images/associates/@Html.DisplayFor(modelItem => item.AssociateImage)">
}
else
{
<h5>No image available</h5>
}
I did something like this for checking to see if an image existed before displaying it.
我做了这样的事情来检查图像在显示之前是否存在。