Basic file management with System.IO in ASP.NET

3.83 (12 votes)

Some basic file and folder management tasks that require the use of classes inside System.IO

string path = Server.MapPath("file.txt");

//Create and write to a file

if (!File.Exists(path))
{

  using (StreamWriter sw = File.CreateText(path))
  {
    sw.Write(@"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Mauris rutrum. 
    Nunc id massa. Pellentesque pretium, tortor eget fermentum tincidunt, eros erat mollis 
    diam, non semper lacus velit et lectus. Proin pharetra, risus in aliquam cursus, felis 
    magna lobortis dolor, at tempus lorem leo ac ipsum. Pellentesque posuere posuere lectus. 

    Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis 
    egestas. Cras aliquam viverra ante. Donec augue lectus, ullamcorper non, euismod sit 
    amet, blandit at, ligula. Donec nec arcu id quam auctor sollicitudin. Duis nunc. Duis 
    nonummy. Vivamus pharetra tortor ac turpis. 

    Integer eros felis, scelerisque vitae, euismod nec, sagittis vitae, urna. Aenean eros 
    metus, gravida sed, tincidunt non, vestibulum sit amet, nisi. Fusce eu quam. Vestibulum 
    non sem id ligula venenatis auctor. Donec vulputate. Aenean ut pede a ligula ornare 
    posuere.");
    sw.WriteLine();
    sw.WriteLine();
    sw.WriteLine("THE END");
  }
}


//Read from the file
try
{
  using (StreamReader sr = new StreamReader(path))
  {
    String line;
    while ((line = sr.ReadLine()) != null)
    {
      Response.Write(line + "<br />");
    }
  }
}
catch (Exception ex)
{
  Response.Write("<p>The file could not be read:");
  Response.Write(ex.Message + "</p>");
}


//Open the file and append more text
try
{
  using (StreamWriter sw = File.AppendText(path))
  {
    sw.Write("Opened the file and added this line on ");
    sw.WriteLine(DateTime.Now);
  }
}
catch (Exception ex)
{
  Response.Write("<p>The file could not be opened:");
  Response.Write(ex.Message + "</p>");
}


// Open the file to read from.
try
{
  using (StreamReader sr = File.OpenText(path))
  {
    String line;
    while ((line = sr.ReadLine()) != null)
    {
      Response.Write(line + "<br />");
    }
  }
}
catch (Exception ex)
{
  Response.Write("<p>The file could not be read:");
  Response.Write(ex.Message + "</p>");
}


//Create new folder/directory

string newpath = Server.MapPath("NewFolder");
try
{
  // Determine whether the directory exists.
  if (Directory.Exists(newpath))
  {
    Response.Write("That path exists already.<br />");
    return;
  }

  // Try to create the directory.
  DirectoryInfo di = Directory.CreateDirectory(newpath);
  string created = Directory.GetCreationTime(newpath).ToString();
  Response.Write("The directory was created at " + created + "<br />");

  // Delete the directory.
  di.Delete();
  Response.Write("The directory was deleted successfully.<br />");
}
catch (Exception ex)
{
  Response.Write("The process failed: " + ex.ToString() + "<br />");
} 


//Recreate folder and copy file to it
try
{
  // Determine whether the directory exists.
  if (Directory.Exists(newpath))
  {
    Response.Write("That path exists already.<br />");
    return;
  }

  // Try to create the directory.
  DirectoryInfo di = Directory.CreateDirectory(newpath);
  string created = Directory.GetCreationTime(newpath).ToString();
  Response.Write("The directory was recreated at " + created + "<br />");
}
catch (Exception ex)
{
  Response.Write("The process failed: " + ex.ToString() + "<br />");
}

string copy = newpath + "\\filecopy.txt";

try
{
  File.Copy(Server.MapPath("file.txt"), copy);
  Response.Write("File successfully copied<br />");
  Response.Write("Created: " + File.GetCreationTime(copy) + "<br />");
  Response.Write("Last Accessed: " + File.GetLastAccessTime(copy) + "<br />");
  Response.Write("Last Written: " + File.GetLastWriteTime(copy) + "<br />");
}
catch (Exception ex)
{
  Response.Write("The process failed: " + ex.ToString() + "<br />");
}

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 20269

0 Comments

Recent Comments

ojorma 17/06/2017 09:24
In response to Razor Pages - The Elevator Pitch
Finally I can say goodbye to webforms...

Mau 06/06/2017 08:58
In response to Razor Pages - The Elevator Pitch
I am missing the razor view code. Thank you for your article. Design pattern should improve the of...

Obinna Okafor 26/05/2017 16:16
In response to Razor Pages - The Elevator Pitch
Thank you for this wonderful piece, Mike. I need more of these...Keep them coming - anything more...

Cyrus 26/05/2017 06:00
In response to Razor Pages - The Elevator Pitch
There are some concern about razor pages performance. Is it faster or slower than MVC? would you a a...

Cyrus 26/05/2017 05:44
In response to Razor Pages - Understanding Handler Methods
well done, thank you....

Satyabrata Mohapatra 23/05/2017 11:41
In response to Razor Pages - Understanding Handler Methods
Nice and easy !! Great post....

Cyrus 16/05/2017 19:55
In response to Razor Pages - Getting Started With The Preview
There is something wrong related to microsoft.dotnetcore.mvc.taghelpers! if you remove it from page...

Cyrus 16/05/2017 10:18
In response to Razor Pages - Getting Started With The Preview
well done mike, it was very useful, I really appreciate that....

Satyabrata Mohapatra 16/05/2017 07:21
In response to Razor Pages - Getting Started With The Preview
Finally!!!! web pages in asp.net core!!! Super excited !!!! Thank u sir for sharing.....Awaiting on...

Daniele 14/03/2017 10:24
In response to Working With Zip Files In ASP.NET MVC
is it possible give to the user a progress bar of the zipping process? Thanks in advance. ...