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

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

0 Comments

Recent Comments

Thomas 05/03/2018 00:59
In response to I'm Not Writing A Book On Razor Pages
There's a typo on this page: = true)] should be [BindProperty(SupportsGet = true)]...

Rolf Herbert 04/03/2018 19:25
In response to I'm Not Writing A Book On Razor Pages
So is MS deprecating razor Web Pages..? Is it dead..? I wish they would stop killing things so its...

Borut 17/02/2018 12:59
In response to I'm Not Writing A Book On Razor Pages
Mike, is it possible that Web Pages and Razor Pages "live" together in one web application? I a I...

hrboyce 09/02/2018 04:44
In response to I'm Not Writing A Book On Razor Pages
Mike, First thanks for doing this but I have to ask, any chance you would consider converting one of...

aziz sallam 07/02/2018 10:18
In response to I'm Not Writing A Book On Razor Pages
u are a great man...

Satyabrata Mohapatra 31/01/2018 11:36
In response to I'm Not Writing A Book On Razor Pages
This is a great news!!!! Thanks...

tangdf 30/01/2018 07:25
In response to I'm Not Writing A Book On Razor Pages
=> { o.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); }); The extension method does...

Obinna Okafor 30/01/2018 04:02
In response to I'm Not Writing A Book On Razor Pages
Thank you very much. I would like to see a project built from scratch using Razor Pages. And it show...

rachida Dukes 31/10/2017 13:52
In response to Customising Identity in Razor Pages
Thanks again for this wonderful tutorial. I followed all the steps in this section called: Adding...

Rachida 31/10/2017 12:06
In response to Customising Identity in Razor Pages
Thanks very much for this wonderful tutorial, it helped a lot....