我正在开发一个应用程序。该应用程序应该从用户那里获得简历,因此我需要一个代码来验证文件是否存在。
我正在使用 ASP.NET / C#。
可以使用命名空间中类的Exists
方法判断指定文件是否存在:File
System.IO
bool System.IO.File.Exists(string path)
您可以在 MSDN 上找到文档。
例子:
using System;
using System.IO;
class Test
{
public static void Main()
{
string resumeFile = @"c:\ResumesArchive\923823.txt";
string newFile = @"c:\ResumesImport\newResume.txt";
if (File.Exists(resumeFile))
{
File.Copy(resumeFile, newFile);
}
else
{
Console.WriteLine("Resume file does not exist.");
}
}
}
要测试文件是否存在于 .NET 中,您可以使用
System.IO.File.Exists (String)
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>
}
我做了这样的事情来检查图像在显示之前是否存在。
尝试这个:
string fileName = "6d294041-34d1-4c66-a04c-261a6d9aee17.jpeg";
string deletePath= "/images/uploads/";
if (!string.IsNullOrEmpty(fileName ))
{
// Append the name of the file to previous image.
deletePath += fileName ;
if (File.Exists(HttpContext.Current.Server.MapPath(deletePath)))
{
// deletevprevious image
File.Delete(HttpContext.Current.Server.MapPath(deletePath));
}
}
简单的回答是你不能——你不能从 ASP 网站检查他们机器上的文件,因为这样做对他们来说是危险的风险。
你必须给他们一个文件上传控制——你可以用这个控制做的不多。出于安全原因,javascript 无法真正触及它。
<asp:FileUpload ID="FileUpload1" runat="server" />
然后他们选择要上传的文件,您必须处理他们可能发送到服务器端的任何空文件。
你可以使用:
System.IO.File.Exists(@"c:\temp\test.txt");
还不能发表评论,但我只是想不同意/澄清erikkallen。
您不应该只在您描述的情况下捕获异常。如果您知道该文件应该在那里并且由于某些特殊情况,它不是,那么尝试访问该文件并捕获发生的任何异常是可以接受的。
但是,在这种情况下,您正在接收来自用户的输入,并且没有理由相信该文件存在。在这里,您应该始终使用 File.Exists()。
我知道这是陈词滥调,但您应该只将异常用于异常事件,而不是作为应用程序正常流程的一部分。它很昂贵,并且使代码更难以阅读/遵循。
这些答案都假设您正在检查的文件位于服务器端。不幸的是,没有铸铁方法可以确保文件存在于客户端(例如,如果您正在上传简历)。当然,你可以在 Javascript 中做到这一点,但你仍然不能 100% 确定在服务器端。
在我看来,处理这个问题的最好方法是假设用户实际上会选择一个合适的文件进行上传,然后做任何你需要做的工作来确保上传的文件是你期望的(提示 - 假设用户正试图用他/她的输入以各种可能的方式毒化你的系统)
你写了 asp.net - 你想上传文件吗?
如果是这样,您可以使用 html
<输入类型="文件" ...
除了 using 之外File.Exists()
,您最好尝试使用该文件并捕获引发的任何异常。该文件可能由于其他原因而无法打开,而不是不存在。
这可能会对您有所帮助。
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; }
我已经在 vb 中编写了这段代码,它可以很好地检查文件是否存在以进行文件上传控制。试试看
对于 VB 代码 ============
If FileUpload1.HasFile = True Then
Dim FileExtension As String = System.IO.Path.GetExtension(FileUpload1.FileName)
If FileExtension.ToLower <> ".jpg" Then
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "Please select .jpg image file to upload"
Else
Dim FileSize As Integer = FileUpload1.PostedFile.ContentLength
If FileSize > 1048576 Then
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File size (1MB) exceeded"
Else
Dim FileName As String = System.IO.Path.GetFileName(FileUpload1.FileName)
Dim ServerFileName As String = Server.MapPath("~/Images/Folder1/" + FileName)
If System.IO.File.Exists(ServerFileName) = False Then
FileUpload1.SaveAs(Server.MapPath("~/Images/Folder1/") + FileUpload1.FileName)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File : " + FileUpload1.FileName + " uploaded successfully"
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File : " + FileName.ToString() + " already exsist"
End If
End If
End If
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "Please select a file to upload"
End If
对于 C# 代码 =======================
if (FileUpload1.HasFile == true) {
string FileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (FileExtension.ToLower != ".jpg") {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Please select .jpg image file to upload";
} else {
int FileSize = FileUpload1.PostedFile.ContentLength;
if (FileSize > 1048576) {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File size (1MB) exceeded";
} else {
string FileName = System.IO.Path.GetFileName(FileUpload1.FileName);
string ServerFileName = Server.MapPath("~/Images/Folder1/" + FileName);
if (System.IO.File.Exists(ServerFileName) == false) {
FileUpload1.SaveAs(Server.MapPath("~/Images/Folder1/") + FileUpload1.FileName);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File : " + FileUpload1.FileName + " uploaded successfully";
} else {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File : " + FileName.ToString() + " already exsist";
}
}
}
} else {
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "Please select a file to upload";
}