Loading

Check Existence of File in ASP.NET and C#

Submitted by: 


We have to check if file exists before doing some things with that particular file. It will prevent error and work flow will be smooth, for this we have to include required namespace i.e system.IO;

  1. Using system.IO;

We have to place these controls on the webpage (ASPX page)

  1. Text box with ID=Textbox1
  2. Button with ID= button1
  3. Label with ID= label1

The logic behind the application will check to see if there is any text in the textbox, this will be like validation check, when the button is clicked, first and foremost. If there is text present, it will check to see if this text is a file in the given folder. The user will be notified if it exists as a file or not.

The source codes for whole page will be given below

  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. using System.Web.UI.WebControls.WebParts;
  9. using System.Web.UI.HtmlControls;
  10. using System.IO;
  11.  
  12. public partial class _Default : System.Web.UI.Page
  13. {
  14. protected void Page_Load(object sender, EventArgs e)
  15. {
  16. if (IsPostBack)
  17. doesFileExist(TextBox1.Text);
  18. }
  19.  
  20. public void doesFileExist(string searchString)
  21. {
  22. if (TextBox1.Text != "")
  23. {
  24. string imageFolder;
  25. imageFolder = Server.MapPath("/media/") + searchString.ToString();
  26. if (File.Exists(imageFolder))
  27. {
  28. Label1.Text = "File <b>" + searchString + "</b> <u>does</u> exist in '/media/' folder.";
  29. }
  30. else
  31. {
  32. Label1.Text = "File <b>" + searchString + "</b> <u>does not</u> exist in '/media/' folder.";
  33. }
  34. }
  35. else
  36. Label1.Text = "Please enter some text.";
  37. }
  38. }

About the author:

PlanetSourceCode.in is a place for all developer providing free source codes, articles, complete projects,complete application in PHP, C/C++, Javascript, Visual Basic, Cobol, Pascal, ASP/VBScript, AJAX, SQL, Perl, Python, Ruby, Mobile Development




Add new comment

Filtered HTML

  • You may insert videos with [video:URL]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.