Tuesday, May 15, 2007

Delete File If Exists Else Create

This Porgarm will delete a file with name Test.txt if exists in the Root Dir, else create a new file with name Test.txt with in the Root dir.FileInfo and File both the classes are available in System.IO namespace.

FileInfo Class
Provides instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects. This class cannot be inherited.

File Class
Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.



Program

protected void btCreate_Click(object sender, EventArgs e)
{
try
{
FileInfo TheFile = new FileInfo(MapPath(".") + "\\" + "Test.txt");
if (TheFile.Exists)
{
File.Delete(MapPath(".") + "\\" + "Test.txt");
}
else
{
File.Create(Server.MapPath(".") + "\\" + "Test.txt");
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}


No comments:

Creative Commons License
Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.