Thursday 9 August 2012

File String Operations


//how to create a text file dynamically            
using System.IO;
string fileLoc = @"c:\sample1.txt";
            FileStream fs = null;
            if (!File.Exists(fileLoc))
            {
                using (fs = File.Create(fileLoc))
                {

                }
            }
(or)
string fileLoc = @"c:\sample1.txt";
FileStream fs= File.Create(fileLoc);
            

//writing to a text file
string fileLoc = @"c:\sample1.txt";
          
              
              
          if (File.Exists(fileLoc))//writing a file
          {
              using (StreamWriter sw = new StreamWriter(fileLoc))
             {
                  sw.Write("Some sample text for the file");
              }
          }

//To Open and read the content from file…
using (StreamReader sr = File.OpenText(path))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
String s=””;
S=sr.ReadLine();
}
}

//Read from file
if (File.Exists(fileLoc))
            {
                using (TextReader tr = new StreamReader(fileLoc))
                {
                    MessageBox.Show(tr.ReadLine());
                }
            }

//copy a file
string fileLocCopy = @"d:\sample1.txt";
            if (File.Exists(fileLoc))
            {
                // If file already exists in destination, delete it.
                if (File.Exists(fileLocCopy))
                    File.Delete(fileLocCopy);
                File.Copy(fileLoc, fileLocCopy);
            }


//Move a File
 string fileLocMove = @"d:\sample1" + System.DateTime.Now.Ticks + ".txt";
            if (File.Exists(fileLoc))
            {
                File.Move(fileLoc, fileLocMove);
            }

//Delete a file
if (File.Exists(fileLoc))
            {
                File.Delete(fileLoc);
            }


// Example #1: Write an array of strings to a file.
// Create a string array that consists of three lines.
            string[] lines = { "First line""Second line""Third line" };
            System.IO.File.WriteAllLines(fileLoc, lines);




// Example #3: Write only some strings in an array to a file.

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
            {
                foreach (string line in lines)
                {
                    if (line.Contains("Second") == false)
                    {
                        file.WriteLine(line);
                    }
                }
            }
// Example #4: Append new text to an existing file
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
            {
                file.WriteLine("Fourth line");
            }  

No comments:

Post a Comment