Home / C Sharp / Archive by category 'C# File Handling'

C# File Handling

Hide a file in C#

File.SetAttributes(filePath, File.GetAttributes(filePath) | FileAttributes.Hidden);

Check if a file is system file in C#

bool isSystem = ((File.GetAttributes(filePath) & FileAttributes.System) == FileAttributes.System);

Check if a file has archive attribute in C#

bool isArchive = ((File.GetAttributes(filePath) & FileAttributes.Archive) == FileAttributes.Archive);

Check whether a file is hidden in C#

bool isHidden = ((File.GetAttributes(filePath) & FileAttributes.Hidden) == FileAttributes.Hidden);

Check if a file is read only in C#

bool isReadOnly = ((File.GetAttributes(filePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);

Delete newly created file from directory in C#

void deleteNewFile(string dirPath)
{
DirectoryInfo directInfo = new DirectoryInfo(dirPath); //read directory to enumerate files
FileInfo[] filelist = directInfo.GetFiles();
 
var fileList = from n in filelist select new { FileName = n.FullName, CreationDate = n.CreationTime.ToLongDateString() }; //get list of files by creationtime
 
var latestFile = (from m in fileList orderby m.CreationDate descending select m.FileName).First<string>(); //get the first file from the sorted list (descending order)
Console.WriteLine(latestFile); //display filename before deleting
 
FileInfo file = new FileInfo(latestFile);
file.Delete();
Console.WriteLine(latestFile + " has been deleted");
Console.ReadKey();
}

Export to excel .csv file using C#

//additional references to import  
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
 
public static void Export_CSV(HttpResponse Response, GridView grid)
    {
        string filename = DateTime.Now.ToString("0:yyyyMMddhhmmss") + ".csv";
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=" + filename);
        Response.Charset = "";
        Response.ContentType = "application/text";
        grid.AllowPaging = false;
        StringBuilder sb = new StringBuilder();
        for (int k = 0; k < grid.Columns.Count; k++)
        {
            sb.Append(grid.Columns[k].HeaderText + ',');
        }
        sb.Append("\r\n");
        for (int i = 0; i < grid.Rows.Count; i++)
        {
            for (int k = 0; k < grid.Columns.Count; k++)
            {
                sb.Append(grid.Rows[i].Cells[k].Text + ',');
            }
            sb.Append("\r\n");
        }
        Response.Output.Write(sb.ToString());
        Response.Flush();
        Response.End();
    }

Export data from gridview to excel in C#

//additional references to import  
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
 
   public static void Export_Excel(HttpResponse Response, GridView grid)
    {
        string filename = DateTime.Now.ToString("0:yyyyMMddhhmmss") + ".xls";
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=" + filename);
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        grid.AllowPaging = false;
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        HtmlForm frm = new HtmlForm();
        grid.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(grid);
        frm.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }

Export data from gridview to PDF in C#

//additional references to import  
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
 
public static void Export_PDF(HttpResponse Response, GridView grid)
    {
 
        string filename = DateTime.Now.ToString("0:yyyyMMddhhmmss") + ".pdf";
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment; filename=" + filename);
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        HtmlForm frm = new HtmlForm();
        grid.AllowPaging = false;
        //grid.DataBind();
        grid.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(grid);
        frm.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
    }

Exporting to microsoft word Using .NET from a GRIDVIEW

Exporting to word using contents from a bound grid view. Please follow the comments for further explanation.

//additional references to import  
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
 
public static void Export_Word(HttpResponse Response, GridView grid)
    {
        //filename for file to be generated
        string filename = DateTime.Now.ToString("0:yyyyMMddhhmmss") + ".doc";
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=" + filename);
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-word ";
        grid.AllowPaging = false;
        //Initialize a new string writer 
        StringWriter sw = new StringWriter();
        //initialize a new HtmlTextWriter 
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        HtmlForm frm = new HtmlForm();
        grid.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(grid);
        frm.RenderControl(hw);
        //write the contents from the grid view 
        Response.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }

Download file from server and manipulate it using C#

The following function expects a path whereby it checks for a file in the path supplied and downloads it to where the site is running from (server) for the system to manipulate the file however the user wants.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;  
 
public class ClsDownload
{
    public ClsDownload()
    {
        //
        // TODO: Add constructor logic here
        //
    }
public void download(string filePath)
    {
        if (File.Exists(filePath))
        {
 
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(filePath));
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.WriteFile(filePath);
            HttpContext.Current.Response.End();
        }
   } }

Monitoring the File System in c# .NET

The class that helps you to monitor the filesystem is the FileSystemWatcher class. It exposes several events that your application can catch. This enables your application to respond to file system events.

The basic procedure for using the FileSystemWatcher is simple. First you must set a handful of properties, which specify where to monitor, what to monitor, and when it should raise the event that your application will handle. Then you give it the addresses of your custom event handlers, so that it can call these when significant events occur. Finally, you turn it on and wait for the events.

Example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
 
namespace FileWatch
{
    public partial class Form1 : Form
    {
        // File System Watcher object.
        private FileSystemWatcher watcher;
        private delegate void UpdateWatchTextDelegate(string newText);
 
        public Form1()
        {
            InitializeComponent();
 
            this.watcher = new FileSystemWatcher();
            this.watcher.Deleted +=
               new FileSystemEventHandler(this.OnDelete);
            this.watcher.Renamed +=
               new RenamedEventHandler(this.OnRenamed);
            this.watcher.Changed +=
               new FileSystemEventHandler(this.OnChanged);
            this.watcher.Created +=
               new FileSystemEventHandler(this.OnCreate);
 
            DirectoryInfo aDir = new DirectoryInfo(@"C:\FileLogs");
            if (!aDir.Exists)
                aDir.Create();
        }
 
              // Utility method to update watch text.
      public void UpdateWatchText(string newText)
      {
         lblWatch.Text = newText;
      }
 
      // Define the event handlers.
      public void OnChanged(object source, FileSystemEventArgs e)
      {
         try
         {
            StreamWriter sw =
               new StreamWriter("C:/FileLogs/Log.txt", true);
            sw.WriteLine("File: {0} {1}", e.FullPath,
                         e.ChangeType.ToString());
            sw.Close();
            this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
               "Wrote change event to log");
         }
         catch (IOException)
         {
            this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
               "Error Writing to log");
         }
      }
 
      public void OnRenamed(object source, RenamedEventArgs e)
      {
         try
         {
            StreamWriter sw =
               new StreamWriter("C:/FileLogs/Log.txt", true);
            sw.WriteLine("File renamed from {0} to {1}", e.OldName,
                         e.FullPath);
            sw.Close();
            this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
               "Wrote renamed event to log");
         }
         catch (IOException)
         {
            this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
               "Error Writing to log");
         }
      }
 
      public void OnDelete(object source, FileSystemEventArgs e)
      {
         try
         {
            StreamWriter sw =
               new StreamWriter("C:/FileLogs/Log.txt", true);
            sw.WriteLine("File: {0} Deleted", e.FullPath);
            sw.Close();
            this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
               "Wrote delete event to log");
         }
         catch (IOException)
         {
            this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
               "Error Writing to log");
         }
      }
 
      public void OnCreate(object source, FileSystemEventArgs e)
      {
         try
         {
            StreamWriter sw =
               new StreamWriter("C:/FileLogs/Log.txt", true);
            sw.WriteLine("File: {0} Created", e.FullPath);
            sw.Close();
            this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
               "Wrote create event to log");
         }
         catch (IOException)
         {
            this.BeginInvoke(new UpdateWatchTextDelegate(UpdateWatchText),
               "Error Writing to log");
         }
      }
 
      private void cmdBrowse_Click(object sender, EventArgs e)
      {
          if (FileDialog.ShowDialog() != DialogResult.Cancel)
          {
              txtLocation.Text = FileDialog.FileName;
              cmdWatch.Enabled = true;
          }
      }
 
      private void cmdWatch_Click(object sender, EventArgs e)
      {
          watcher.Path = Path.GetDirectoryName(txtLocation.Text);
          watcher.Filter = Path.GetFileName(txtLocation.Text);
          watcher.NotifyFilter = NotifyFilters.LastWrite |
             NotifyFilters.FileName | NotifyFilters.Size;
          lblWatch.Text = "Watching " + txtLocation.Text;
          // Begin watching.
          watcher.EnableRaisingEvents = true;
      }
    }
}

Reading and Writing Compressed Files in c# .NET

The two compression stream classes in the System.IO.Compression namespace are DeflateStream and GZipStream. They work very similarly. In both cases, you initialize them with an existing stream, which, in the case of files, will be a FileStream object. After this you can use them with StreamReader and StreamWriter just like any other stream. All you need to specify in addition to that is whether the stream will be used for compression (saving files) or decompression (loading files) so that the class knows what to do with the data that passes through it.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
 
namespace Compressor
{
    class Program
    {
        static void SaveCompressedFile(string filename, string data)
        {
            FileStream fileStream =
               new FileStream(filename, FileMode.Create, FileAccess.Write);
            GZipStream compressionStream =
               new GZipStream(fileStream, CompressionMode.Compress);
            StreamWriter writer = new StreamWriter(compressionStream);
            writer.Write(data);
            writer.Close();
        }
 
        static string LoadCompressedFile(string filename)
        {
            FileStream fileStream =
               new FileStream(filename, FileMode.Open, FileAccess.Read);
            GZipStream compressionStream =
               new GZipStream(fileStream, CompressionMode.Decompress);
            StreamReader reader = new StreamReader(compressionStream);
            string data = reader.ReadToEnd();
            reader.Close();
            return data;
        }
 
        static void Main(string[] args)
        {
            try
            {
                string filename = "compressedFile.txt";
 
                Console.WriteLine(
                   "Enter a string to compress (will be repeated 100 times):");
                string sourceString = Console.ReadLine();
                StringBuilder sourceStringMultiplier =
                   new StringBuilder(sourceString.Length * 100);
                for (int i = 0; i < 100; i++)
                {
                    sourceStringMultiplier.Append(sourceString);
                }
                sourceString = sourceStringMultiplier.ToString();
                Console.WriteLine("Source data is {0} bytes long.", sourceString.Length);
 
                SaveCompressedFile(filename, sourceString);
                Console.WriteLine("\nData saved to {0}.", filename);
 
                FileInfo compressedFileData = new FileInfo(filename);
                Console.WriteLine("Compressed file is {0} bytes long.",
                                  compressedFileData.Length);
 
                string recoveredString = LoadCompressedFile(filename);
                recoveredString = recoveredString.Substring(
                   0, recoveredString.Length / 100);
                Console.WriteLine("\nRecovered data: {0}", recoveredString);
 
                Console.ReadKey();
            }
            catch (IOException ex)
            {
                Console.WriteLine("An IO exception has been thrown!");
                Console.WriteLine(ex.ToString());
                Console.ReadKey();
            }
        }
    }
}

Working with Comma-Separated Values in C# .NET

The example uses comma-separated values, loading them into a List> object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
 
namespace CommaValues
{
    class Program
    {
        private static List<Dictionary<string, string>> GetData(
   out List<string> columns)
        {
            string line;
            string[] stringArray;
            char[] charArray = new char[] { ',' };
            List<Dictionary<string, string>> data =
               new List<Dictionary<string, string>>();
            columns = new List<string>();
 
            try
            {
                FileStream aFile = new FileStream(@"SomeData.txt", FileMode.Open);
                StreamReader sr = new StreamReader(aFile);
 
                // Obtain the columns from the first line.
                // Split row of data into string array
                line = sr.ReadLine();
                stringArray = line.Split(charArray);
 
                for (int x = 0; x <= stringArray.GetUpperBound(0); x++)
                {
                    columns.Add(stringArray[x]);
                }
 
                line = sr.ReadLine();
                while (line != null)
                {
                    // Split row of data into string array
                    stringArray = line.Split(charArray);
                    Dictionary<string, string> dataRow = new Dictionary<string, string>();
 
                    for (int x = 0; x <= stringArray.GetUpperBound(0); x++)
                    {
                        dataRow.Add(columns[x], stringArray[x]);
                    }
 
                    data.Add(dataRow);
 
                    line = sr.ReadLine();
                }
 
                sr.Close();
                return data;
            }
            catch (IOException ex)
            {
                Console.WriteLine("An IO exception has been thrown!");
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
                return data;
            }
        }
 
        static void Main(string[] args)
        {
            List<string> columns;
            List<Dictionary<string, string>> myData = GetData(out columns);
 
            foreach (string column in columns)
            {
                Console.Write("{0,-20}", column);
            }
            Console.WriteLine();
 
            foreach (Dictionary<string, string> row in myData)
            {
                foreach (string column in columns)
                {
                    Console.Write("{0,-20}", row[column]);
                }
                Console.WriteLine();
            }
            Console.ReadKey();
        }
    }
}

Reading Data from an Input Stream in C# .NET

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
 
namespace StreamRead
{
    class Program
    {
        static void Main(string[] args)
        {
            string line;
 
            try
            {
                FileStream aFile = new FileStream("Log.txt", FileMode.Open);
                StreamReader sr = new StreamReader(aFile);
                line = sr.ReadLine();
                // Read data in line by line.
                while (line != null)
                {
                    Console.WriteLine(line);
                    line = sr.ReadLine();
                }
                sr.Close();
            }
            catch (IOException e)
            {
                Console.WriteLine("An IO exception has been thrown!");
                Console.WriteLine(e.ToString());
                return;
            }
            Console.ReadKey();
        }
    }
}

Reading Data from Random Access Files

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
 
namespace ReadFile
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] byData = new byte[200];
            char[] charData = new Char[200];
 
            try
            {
                FileStream aFile = new FileStream("sometext.txt", FileMode.Open);
                aFile.Seek(113, SeekOrigin.Begin);
                aFile.Read(byData, 0, 200);
            }
            catch (IOException e)
            {
                Console.WriteLine("An IO exception has been thrown!");
                Console.WriteLine(e.ToString());
                Console.ReadKey();
                return;
            }
 
            Decoder d = Encoding.UTF8.GetDecoder();
            d.GetChars(byData, 0, byData.Length, charData, 0);
 
            Console.WriteLine(charData);
            Console.ReadKey();
        }
    }
}

Writing Data to Random Access Files

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
 
namespace WriteFile
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] byData;
            char[] charData;
 
            try
            {
                FileStream aFile = new FileStream("Temp.txt", FileMode.Create);
                charData = "Hello and welcome to w3mentor.com".ToCharArray();
                byData = new byte[charData.Length];
                Encoder e = Encoding.UTF8.GetEncoder();
                e.GetBytes(charData, 0, charData.Length, byData, 0, true);
 
                // Move file pointer to beginning of file.
                aFile.Seek(0, SeekOrigin.Begin);
                aFile.Write(byData, 0, byData.Length);
            }
            catch (IOException ex)
            {
                Console.WriteLine("An IO exception has been thrown!");
                Console.WriteLine(ex.ToString());
                Console.ReadKey();
                return;
            }
        }
    }
}

Writing Data to an Output Stream in C# .NET

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
 
namespace StreamWrite
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                FileStream aFile = new FileStream("Logfile.txt", FileMode.OpenOrCreate);
                StreamWriter sw = new StreamWriter(aFile);
 
                bool truth = true;
                // Write data to file.
 
                sw.WriteLine("It is now {0} and things are looking good.",
                             DateTime.Now.ToLongDateString());
 
                sw.Close();
            }
            catch (IOException e)
            {
                Console.WriteLine("An IO exception has been thrown!");
                Console.WriteLine(e.ToString());
                Console.ReadLine();
                return;
            }
        }
    }
}

Read file path from commandline and displays information about file and directory

The following example console application takes a file path from a commandline argument and then displays information about the file and the containing directory.

using System;
using System.IO;
 
public class FileInform {
 
    private static void Main(string[] args) {
 
        if (args.Length == 0) {
 
            Console.WriteLine("Please supply a file name.");
            return;
        }
 
        FileInfo file = new FileInfo(args[0]);
 
        // Display file information.
        Console.WriteLine("Checking file: " + file.Name);
        Console.WriteLine("File exists: " + file.Exists.ToString());
 
        if (file.Exists) {
 
            Console.Write("File created: ");
            Console.WriteLine(file.CreationTime.ToString());
            Console.Write("File last updated: ");
            Console.WriteLine(file.LastWriteTime.ToString());
            Console.Write("File last accessed: ");
            Console.WriteLine(file.LastAccessTime.ToString());
            Console.Write("File size (bytes): ");
            Console.WriteLine(file.Length.ToString());
            Console.Write("File attribute list: ");
            Console.WriteLine(file.Attributes.ToString());
 
        }
        Console.WriteLine();
 
        // Display directory information.
        DirectoryInfo dir = file.Directory;
 
        Console.WriteLine("Checking directory: " + dir.Name);
        Console.WriteLine("In directory: " + dir.Parent.Name);
        Console.Write("Directory exists: ");
        Console.WriteLine(dir.Exists.ToString());
 
        if (dir.Exists) {
            Console.Write("Directory created: ");
            Console.WriteLine(dir.CreationTime.ToString());
            Console.Write("Directory last updated: ");
            Console.WriteLine(dir.LastWriteTime.ToString());
            Console.Write("Directory last accessed: ");
            Console.WriteLine(dir.LastAccessTime.ToString());
            Console.Write("Directory attribute list: ");
            Console.WriteLine(dir.Attributes.ToString());
            Console.WriteLine("Directory contains: " + 
              dir.GetFiles().Length.ToString() + " files");
        }
 
        Console.ReadLine();
    }
}

Read data from a WebResponse in csharp

//After a webrequest..
 
WebResponse response = request.GetResponse( );
 
using (StreamReader reader = new StreamReader(response.GetResponseStream( ))) {
  while (reader.Peek( ) != -1) {
    Console.WriteLine(reader.ReadLine( ));
  }
}