C# 验证文件是否存在

发布于 2024-07-10 20:11:50 字数 88 浏览 12 评论 0原文

我正在开发一个应用程序。 该应用程序应该从用户那里获取简历,因此我需要一个代码来验证文件是否存在。

我正在使用 ASP.NET / C#。

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#.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

夕色琉璃 2024-07-17 20:11:51

要测试.NET中是否存在文件,可以使用

System.IO.File.Exists (String)

To test whether a file exists in .NET, you can use

System.IO.File.Exists (String)
笙痞 2024-07-17 20:11:51
    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> 
      }

我做了类似的事情来检查图像在显示之前是否存在。

    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.

过潦 2024-07-17 20:11:51

尝试这个:

     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));
            }
        }

Try this:

     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));
            }
        }
所谓喜欢 2024-07-17 20:11:51

简单的答案是您不能 - 您将无法从 ASP 网站检查其计算机上的文件,因为这样做对他们来说将是一个危险的风险。

您必须为他们提供文件上传控件 - 并且您对该控件无能为力。 出于安全原因,javascript 无法真正触及它。

<asp:FileUpload ID="FileUpload1" runat="server" />

然后他们选择要上传的文件,您必须处理他们可能发送到服务器端的任何空文件。

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.

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.

<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.

七堇年 2024-07-17 20:11:51

你可以使用:

System.IO.File.Exists(@"c:\temp\test.txt");

You could use:

System.IO.File.Exists(@"c:\temp\test.txt");
街角迷惘 2024-07-17 20:11:51

还不能发表评论,但我只是想不同意/澄清 erikkallen。

您不应该仅仅在您所描述的情况下捕获异常。 如果您知道该文件应该在那里,但由于某些异常情况,它不在那里,那么尝试访问该文件并捕获发生的任何异常是可以接受的。

然而,在这种情况下,您正在接收来自用户的输入,并且没有理由相信该文件存在。 在这里您应该始终使用 File.Exists()。

我知道这是陈词滥调,但您应该只将异常用于特殊事件,而不是作为应用程序正常流程的一部分。 它很昂贵并且使代码更难以阅读/遵循。

Can't comment yet, but I just wanted to disagree/clarify with 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 exceptional case, 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().

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.

情话已封尘 2024-07-17 20:11:51

这些答案都假设您正在检查的文件位于服务器端。 不幸的是,没有一种可靠的方法可以确保文件存在于客户端(例如,如果您正在上传简历)。 当然,您可以用 Javascript 来完成,但您仍然无法在服务器端 100% 确定。

在我看来,处理这个问题的最好方法是假设用户实际上会选择一个合适的文件进行上传,然后做任何你需要做的工作以确保上传的文件是你所期望的(提示 - 假设用户试图用他/她的输入以各种可能的方式毒害你的系统)

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.

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)

情徒 2024-07-17 20:11:51

您编写了 asp.net - 您想要上传文件吗?
如果是这样你可以使用html

<输入类型=“文件”...

You wrote asp.net - are you looking to upload a file?
if so you can use the html

<input type="file" ...

人│生佛魔见 2024-07-17 20:11:51

除了使用 File.Exists() 之外,您最好尝试使用该文件并捕获引发的任何异常。 文件可能因不存在以外的其他原因而无法打开。

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.

浅沫记忆 2024-07-17 20:11:51

这可能对你有帮助。

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; }

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; }
云淡风轻 2024-07-17 20:11:51

我用 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";
}

I have written this code in vb and its is working fine to check weather a file is exists or not for fileupload control. try it

FOR VB CODE ============

    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

FOR C# CODE ======================

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";
}
酒废 2024-07-17 20:11:50

您可以使用 System.IO 命名空间中的 File 类的 Exists 方法判断指定文件是否存在:

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.");
        }
    }
}

You can determine whether a specified file exists using the Exists method of the File class in the System.IO namespace:

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:\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.");
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文