Saturday 27 July 2013

FILE HANDLIGN IN C# .NET



          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 filehandling
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }



        private void write_Click(object sender, EventArgs e)
        {
           // FileStream fs = new FileStream(@"f:\xyz.txt", FileMode.CreateNew, FileAccess.Write);
            FileStream fs = new FileStream(@"D:\" + textBox3.Text + "", FileMode.CreateNew, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(textBox1.Text);
            sw.Flush();
            sw.Close();
            MessageBox.Show("file created");

        }

        private void read_Click(object sender, EventArgs e)
        {
            //FileStream fs = new FileStream(@"f:\xyz.txt", FileMode.Open, FileAccess.Read);
            FileStream fs = new FileStream(@""+textBox3.Text+"", FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);
            textBox2.Text = sr.ReadToEnd();
            sr.Close();
        }

        private void past_Click(object sender, EventArgs e)
        {
            FileInfo fi = new FileInfo(@"f:\xyz.txt");
            if (fi.Exists)
            {
                fi.CopyTo(@"f:\ab1.txt");
                MessageBox.Show("file past sucessfully");
            }
        }

        private void move_Click(object sender, EventArgs e)
        {
            FileInfo fi=new FileInfo(@"f:\xyz.txt");
            if (fi.Exists)
            {
                fi.MoveTo(@"d:\xyz.txt");
                MessageBox.Show("file move");
            }
          

        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            textBox3.Text = openFileDialog1.FileName.ToString();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog1.ShowDialog();
        }

        private void delete_Click(object sender, EventArgs e)
        {
            FileInfo fi = new FileInfo(@"f:\ab1.txt");
            if (fi.Exists)
            {
                fi.Delete();
                MessageBox.Show("dile is deleted");
            }
        }

   // to add  all drives in a combo box from your system
        private void driveinfo_Click(object sender, EventArgs e)
        {
            DriveInfo[] dr = DriveInfo.GetDrives();
         
            for (int a = 0; a < dr.Length; a++)
            {
                comboBox1.Items.Add(dr[a].ToString());
            }

        }
  /;/ to got the drive information
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            DriveInfo dd = new DriveInfo(comboBox1.SelectedItem.ToString());
            MessageBox.Show("total size of \t" +dd.TotalSize.ToString());
            MessageBox.Show("free size " +dd.AvailableFreeSpace.ToString());
            MessageBox.Show(dd.DriveFormat.ToString());
            MessageBox.Show(dd.TotalFreeSpace.ToString());
            MessageBox.Show(dd.VolumeLabel.ToString());
             MessageBox.Show(dd.Name.ToString());
              MessageBox.Show(dd.RootDirectory.ToString());
        }
        }
    }
//read all words from all lines

private void button3_Click(object sender, EventArgs e)
        {
           StreamReader reader = new StreamReader(@"D:\h2.txt");
          
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    // Do something with line
                    string[] parts = line.Split(',');

                    foreach(string a in parts)
                    {
                        listBox1.Items.Add(a);
                    }
                }
            }

//read all text
private void button3_Click(object sender, EventArgs e)
        {
          
string file = File.ReadAllText("C:\\file.txt");
     Console.WriteLine(file);
}



//read all lines
private void button3_Click(object sender, EventArgs e)
        {
       
string[] lines = File.ReadAllLines("file.txt");
     foreach (string line in lines)
     {
         // Do something with line
         if (line.Length > 80)
         {
    }
     }
//To add item in a listcollection from a file
Button _click
{
List<string> fileLines = File.ReadAllLines("file.txt").ToList();
}
// to count no. of lines in a file
 
private void button4_Click(object sender, EventArgs e)
        {
            //List<string> fileLines = File.ReadAllLines(@"d:\\h2.txt").ToList();
            int lineCount = File.ReadAllLines(@"d:\\h2.txt").Length;
            MessageBox.Show(lineCount.ToString());
           
        }
 
// to find a string value from a file

            bool exists = (from line in File.ReadAllLines(@"D:\\h2.txt")
                           where line == "1,pawan,324234"
                           select line).Count() > 0;
            MessageBox.Show(exists.ToString());

// write file from a array

       string[] stringArray = new string[]
       {
           "cat",
           "dog",
           "arrow"
       };
            File.WriteAllLines(@"D:\h3.txt", stringArray);


File handling in C#

File handling is an unmanaged resource in your application system. It is outside your application domain (unmanaged resource). It is not managed by CLR.

Data is stored in two ways, persistent and non-persistent manner.

When you open a file for reading or writing, it becomes stream.

Stream: Stream is a sequence of bytes traveling from a source to a destination over a communication path.

The two basic streams are input and output streams. Input stream is used to read and output stream is used to write.

The System.IO namespace includes various classes for file handling.

The parent class of file processing is stream. Stream is an abstract class, which is used as the parent of the classes that actually implement the necessary operations.

The primary support of a file as an object is provided by a .NET Framework class called File. This static class is equipped with various types of (static) methods to create, save, open, copy, move, delete, or check the existence of a file.

Diagram to represent file-handling class hierarchy 
 


Note: FileInfo, DirectoryInfo and DriveInfo classes have instance methods. File, Directory, Path classes have static methods.

The following table describes some commonly used classes in the System.IO namespace.

Class Name
Description

FileStream

It is used to read from and write to any location within a file
BinaryReader
It is used to read primitive data types from a binary stream
BinaryWriter
It is used to write primitive data types in binary format
StreamReader
It is used to read characters from a byte Stream
StreamWriter
It is used to write characters to a stream.
StringReader
It is used to read from a string buffer
StringWriter
It is used to write into a string buffer
DirectoryInfo
It is used to perform operations on directories
FileInfo
It is used to perform operations on files

Reading and writing in the text file


StreamWriter Class


The StreamWriter class in inherited from the abstract class TextWriter. The TextWriter class represents a writer, which can write a series of characters.

The following table describes some of the methods used by StreamWriter class.

Methods
Description
Close
Closes the current StreamWriter object and the underlying stream

Flush

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream

Write

Writes to the stream

WriteLine

Writes data specified by the overloaded parameters, followed by end of line

Program to write user input to a file using StreamWriter Class


using System;
using System.Text;
using System.IO;

namespace FileWriting_SW
{
    class Program
    {
        class FileWrite
        {
            public void WriteData()
            {
                FileStream fs = new FileStream("c:\\test.txt", FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                Console.WriteLine("Enter the text which you want to write to the file");
                string str = Console.ReadLine();
                sw.WriteLine(str);
                sw.Flush();
                sw.Close();
                fs.Close();
            }
        }
        static void Main(string[] args)
        {
            FileWrite wr = new FileWrite();
            wr.WriteData();
        }
    }
}

StreamReader Class


The StreamReader class is inherited from the abstract class TextReader. The TextReader class represents a reader, which can read series of characters.

The following table describes some methods of the StreamReader class.

Methods
Description
Close
Closes the object of StreamReader class and the underlying stream, and release any system resources associated with the reader
Peek
Returns the next available character but doesn't consume it
Read
Reads the next character or the next set of characters from the stream
ReadLine
Reads a line of characters from the current stream and returns data as a string
Seek
Allows the read/write position to be moved to any position with the file

Program to read from a file using StreamReader Class


using System;
using System.IO;

namespace FileReading_SR
{
    class Program
    {
        class FileRead
        {
            public void ReadData()
            {
                FileStream fs = new FileStream("c:\\test.txt", FileMode.Open, FileAccess.Read);
                StreamReader sr = new StreamReader(fs);
                Console.WriteLine("Program to show content of test file");
                sr.BaseStream.Seek(0, SeekOrigin.Begin);
                string str = sr.ReadLine();
                while (str != null)
                {
                    Console.WriteLine(str);
                    str = sr.ReadLine();
                }
                Console.ReadLine();
                sr.Close();
                fs.Close();
            }
        }
        static void Main(string[] args)
        {
            FileRead wr = new FileRead();
            wr.ReadData();

        }
    }
}




  StreamWriter myFile = File.CreateText("hello.txt");
 
            myFile.WriteLine("Hello");
            myFile.WriteLine("This is a text file");
            myFile.WriteLine("Goodbye");
            myFile.Close();


public WriteFileBinary()
        {
 
            string name;
            int[] scores = new int[3];
 
            Console.WriteLine("Enter your student name :");
            name = Console.ReadLine();
 
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("Enter score {0} ", i+1);
                scores[i] = Convert.ToInt32(Console.ReadLine());
            }
 
            FileStream myFile = new FileStream("hello.bin", FileMode.Create);
 
            BinaryWriter filedata = new BinaryWriter(myFile);
 
            filedata.Write(name);
 
            for (int i = 0; i < 3; i++)
            {
                filedata.Write(scores[i]);
            }
 
            filedata.Close();
            myFile.Close();
 
        }
//Read a binary file
    public class ReadFileBinary
    {
 
        public ReadFileBinary()
        {
 
            string name;
            int[] scores = new int[3];
 
            FileStream myFile = new FileStream("hello.bin", FileMode.Open);
 
            BinaryReader filedata = new BinaryReader(myFile);
 
            name = filedata.ReadString();
 
            for (int i = 0; i < 3; i++)
            {
                scores[i] = filedata.ReadInt32();
            }
 
            filedata.Close();
            myFile.Close();
 
 
            Console.WriteLine("Information from file");
            Console.WriteLine("Name {0} :", name);
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("Score {0}, {1}", i + 1, scores[i]);
            }
 
        }


File.WriteAllText
A very simple method to call, the File.WriteAllText method receives two arguments: the path of the output file, and the exact string contents of the text file. If you need to create a simple text file, this is an ideal method.
Program that uses File.WriteAllText [C#]

using System.IO;

class Program
{
    static void Main()
    {
     File.WriteAllText("C:\\perls.txt",
         "Dot Net Perls");
    }
}
Result:The C:\perls.txt contains the string "Dot Net Perls".
StreamReader
Two of the most useful types for handling files in the C# language and .NET Framework are the StreamReader and StreamWriter types. They are described here. Often you achieve better performance with StreamReader and StreamWriter than with static File methods.
Program that uses ReadLine [C#]

using System.IO;

class Program
{
    static void Main()
    {
     // Read in every line in the file.
     using (StreamReader reader = new StreamReader("file.txt"))
     {
         string line;
         while ((line = reader.ReadLine()) != null)
         {
           // Do something with line
           string[] parts = line.Split(',');
         }
     }
    }
}
Result:The lines in the text file are read in and separated on commas.
File.ReadAllText
This simple program uses the File.ReadAllText method to load in the file "file.txt" on the C: volume. Then it prints the contents of the file, which are now stored in a string object.
System.IO namespace [C#]

//
// Include this namespace for all the examples.
//
using System.IO;

Program that reads in file [C#]

using System;
using System.IO;

class Program
{
    static void Main()
    {
     string file = File.ReadAllText("C:\\file.txt");
     Console.WriteLine(file);
    }
}
Output:The program writes the contents of the file to the console.
File.ReadAllLines
Here you want to read all the lines in from a file and place them in an array. The following code reads in each line in the file "file.txt" into an array. This is efficient code. We provide performance information later on.
Program that uses ReadAllLines [C#]

using System.IO;

class Program
{
    static void Main()
    {
     // Read in every line in specified file.
     // ... This will store all lines in an array in memory,
     // ... which you may not want or need.
     string[] lines = File.ReadAllLines("file.txt");
     foreach (string line in lines)
     {
         // Do something with line
         if (line.Length > 80)
         {
           // Example code
         }
     }
    }
}
Result:We loop over lines in the file. And then we test the length of each line.
Performance. When you read in a file with File.ReadAllLines, many strings are allocated and put into an array in a single method call. With StreamReader, however, you can allocate each string as you pass over the file by calling ReadLine. This makes StreamReader more efficient unless you need all the file data in memory at once.
Read into List. We look at a usage of the List constructed type with file handling methods. List and ArrayList are extremely useful data structures for C# programmers—they allow object collections to rapidly expand or shrink. Here we look at how you can use LINQ to get a List of lines from a file in one line.
Program that uses ReadAllLines with List [C#]

using System.Collections.Generic;
using System.IO;
using System.Linq;

class Program
{
    static void Main()
    {
     // Read in all lines in the file,
     // ... and then convert to a List with LINQ.
     List<string> fileLines = File.ReadAllLines("file.txt").ToList();
    }
}
Count lines. Here we need to count the number of lines in a file but don't want to write lots of code to do it. Note that the example here doesn't have ideal performance characteristics. We reference the Length property on the array returned.
Program that counts lines [C#]

using System.IO;

class Program
{
    static void Main()
    {
     // Another method of counting lines in a file.
     // ... This is not the most efficient way.
     // ... It counts empty lines.
     int lineCount = File.ReadAllLines("file.txt").Length;
    }
}
Query example. Does a line containing a specific string exist in the file? Maybe you want to see if a name or location exists in a line in the file. Here we can harness the power of LINQ to find any matching line. See also the Contains method on the List type.
Program that uses LINQ on file [C#]

using System.IO;
using System.Linq;

class Program
{
    static void Main()
    {
     // One way to see if a certain string is a line
     // ... in the specified file. Uses LINQ to count elements
     // ... (matching lines), and then sets |exists| to true
     // ... if more than 0 matches were found.
     bool exists = (from line in File.ReadAllLines("file.txt")
                  where line == "Some line match"
                  select line).Count() > 0;
    }
}
File.ReadLines
In constrast to File.ReadAllLines, File.ReadLines does not read in every line immediately upon calling it. Instead, it reads lines only as they are needed. It is best used in a foreach-loop.
File.WriteAllLines
Here we look at how you can write an array to a file. When you are done with your in-memory processing, you often need to write the data to disk. Fortunately the File class offers an excellent WriteAllLines method. It receives the file path and then the array to write. This will replace all the file contents.
Program that writes array to file [C#]

using System.IO;

class Program
{
    static void Main()
    {
     // Write a string array to a file.
     string[] stringArray = new string[]
     {
         "cat",
         "dog",
         "arrow"
     };
     File.WriteAllLines("file.txt", stringArray);
    }
}

Output

cat
dog
arrow
File.WriteAllText
A very simple method to call, the File.WriteAllText method receives two arguments: the path of the output file, and the exact string contents of the text file. If you need to create a simple text file, this is an ideal method.
Program that uses File.WriteAllText [C#]

using System.IO;

class Program
{
    static void Main()
    {
     File.WriteAllText("C:\\perls.txt",
         "Dot Net Perls");
    }
}
Result:The C:\perls.txt contains the string "Dot Net Perls".
File.AppendAllText
Here we mention a way you can append text to files in a simple method. The previous example will replace the file's contents, but for a log file or error listing, we must append to the file. Note that we could read in the file, append to that in memory, and then write it out completely again. That is slow.
File.AppendText
The File.AppendText method returns a StreamWriter instance that you can use to append string data to the specified file. It is not covered on this site in detail. It is usually easier to use the StreamWriter constructor directly.
File.ReadAllBytes
Here we use File.ReadAllBytes to read in an image, PNG, to memory. One example usage of this sample is to cache an image in memory for performance. This works very well and greatly outperforms reading in the image each time.
Program that caches binary file [C#]

static class ImageCache
{
    static byte[] _logoBytes;
    public static byte[] Logo
    {
     get
     {
         // Returns logo image bytes.
         if (_logoBytes == null)
         {
           _logoBytes = File.ReadAllBytes("Logo.png");
         }
         return _logoBytes;
     }
    }
}
File.WriteAllBytes
The File.WriteAllBytes method does exactly as you might expect: it writes the bytes in a byte array to a file at the location you specify. You can see an example method that compresses byte data.
TextReader/TextWriter
The TextReader and TextWriter types form the base class that other, more useful types derive from. They are not really useful on their own most of the time.
BinaryReader/BinaryWriter
The .NET Framework has two types that can make reading or writing a binary file much easier: the BinaryReader and BinaryWriter types. These abstract data types make it unnecessary for you to ever have to deal with the raw bits and bytes yourself.
CSV files
Comma-separated values files are text-based databases. With the System.IO namespace, you can read them into your C# program. The TextFieldParser type is also available, but may incur a performance loss.
File equality
How can you tell if two files are exactly equal? Unfortunately, the file system's metadata is not sufficient. For this reason, using the File.ReadAllBytes method and comparing the byte arrays is necessary.
Directory
You can manipulate directories on the file system with your C# program. The Directory static type is necessary for this. You can also test to see if a directory exists.
Manipulate files
You can copy, delete, rename or get time information about files using the C# programming language. These actions are available through the File type as well as the FileInfo type.
Seek
You can seek to a specific location in your file with the Seek method. We demonstrate this method and provide a detailed benchmark of its best usage.
FileInfo
You can get information about a file from the file system with the FileInfo type. This does not require you to load the entire file into memory. It does access the storage unit however.
Sizes
There are other ways to get the sizes of files and directories—you can do this in different ways depending on what objects you are using to manipulate the file. You can often determine file lengths without reading in the entire file.
Stream
Streams take many forms in the .NET Framework. Sometimes leaving a file on the disk would impact performance or stability in a negative way. In these cases, you can use a MemoryStream to store a file in memory in Stream format. This is described further.
WebClient
Not every file you want to use is always located on your local disk. Instead you may need to access the network to download a file from a remote computer. The WebClient type provides a way for you to do this.
Office
It is common to need to control Microsoft Excel with C# code. We first introduce an approach to Excel interop that is very fast. Microsoft Word is also controllable with the interop assemblies. We show how to read in each word from a document in a loop.
MemoryMappedFile
It is possible in version 4.0 of the .NET Framework to map files into memory with the MemoryMappedFile class. We present a benchmark that reveals the performance advantage of using MemoryMappedFile.
Performance
Most every time you access a file in Windows, the operating system puts that file into a memory cache. We provide a benchmark of file system caches. We dive into how temporal locality can be used to improve performance.
Summary
We saw several methods and patterns for using System.IO in the C# programming language. The .NET Framework is excellent with file handling. Nearly every medium or larger size program will need to use file input/output. We demonstrated some of the clearest methods for this purpose.





Creating Objects
Creating a DirectoryInfo or FileInfo object is very simple. The constructor takes the path to the file.
DirectoryInfo di = new DirectoryInfo("C:\\Windows");
FileInfo fi = new FileInfo("C:\\Windows\\Notepad.exe");
Listing All Files in a Directory
The following code snippet lists all the files in the C:\Windows directory.
1
2
3
4
5
6
DirectoryInfo di = new DirectoryInfo("C:\\Windows");
FileInfo[] fis = di.GetFiles();
foreach (FileInfo fi in fis)
{
    Console.WriteLine(fi.Name);
}

Implementing Binary Read & Write
The StreamReader and StreamWriter classes work with character data. In this mode everything is written as plain text. To implement binary operations, wherein a number such as 327.68 would be written as a float value consuming four bytes and not just as plain text, we need to use the BinaryReader and BinaryWriter classes.
They are very similar to their text counterparts except that no Line (ReadLine and WriteLine) methods are provided. The BinaryReader class also supports data type specific methods such as ReadInt32, ReadDouble, etc. These allow you to directly read the content from the file in the appropriate format. If we were to use the StreamReader class, we would have to convert the string to integer or double format using the Convert.ToInt32 and Convert.ToDouble methods.
Writing to File
1
2
3
int MyNumber = 69;
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(MyNumber);
Reading from file
1
2
BinaryReader br = new BinaryReader(fs);
int MyNumber = br.ReadInt32();
Imple


No comments:

Post a Comment