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: 20305

0 Comments

Recent Comments

Satyabrata Mohapatra 23/07/2017 16:43
In response to Razor Pages - The Elevator Pitch
@Dale Severin You can continue to build apps using asp.net web pages....

Satyabrata Mohapatra 23/07/2017 16:40
In response to Sending Email in Razor Pages
Thanks for sharing...learned a lot...

Gfw 22/07/2017 11:53
In response to Sending Email in Razor Pages
Question... Does System.Net.Mail support SSL?...

Dale Severin 20/07/2017 03:38
In response to Razor Pages - The Elevator Pitch
I work with razor web pages extensively. I appreciate the rapid development it permits me to I am as...

Obinna Okafor 14/07/2017 01:19
In response to Routing in Razor Pages
Thank you, Mike. Good post....

Satyabrata Mohapatra 11/07/2017 16:02
In response to Routing in Razor Pages
Very powerful routing system!!...

Cyrus 05/07/2017 03:41
In response to Razor Pages - Getting Started With The Preview
How can I trim packages and services as much as possible to use just razor pages? I don’t want to to...

Harris Boyce 04/07/2017 04:17
In response to Razor Pages - The Elevator Pitch
As a developer of a couple "trivial" web pages applications used by non-profits that wouldn't have I...

Cyrus 28/06/2017 20:25
In response to Razor Pages - Getting Started With The Preview
.net core 2.0 preview 2: <a...

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