locked
how to read .dat file RRS feed

  • Question

  •  

    hi

     

    i have .dat file to work with.

    it has approax 150 char per line.

     

    i have to read it line by line and make appropriate changes in it.

    e.g. say 100th char is 1 so i have to make it 0.

     

    any help/example appreciated...

     

    Monday, October 22, 2007 12:11 PM

Answers

  • File.ReadAllLines is your friend!

     

    string[] lines = System.IO.File.ReadAllLines(@"C:\MyFile.dat");

    foreach (string line in lines)

    {

    if ('0' == line[100])

    {

    line[100] = '1';

    }

    }

     

    In VS 2008, to query over semi-structured data in text files, you can also use LINQ. For example, to create a new file that contains only those lines where line[100] = 0, you would write:

     

    string[] lines = System.IO.File.ReadAllLines(@"C:\MyFile.dat");

    var query = from line in lines

    where line[100] == '0'

    select line;

    System.IO.File.WriteAllLines(@"C:\MyNewFile.dat", query.ToArray());

     

    See http://msdn2.microsoft.com/en-us/library/bb397915(VS.90).aspx for more examples.

                      

    Tuesday, October 23, 2007 6:50 PM

All replies

  • if it's just text file, you can use any text reader/writer like StreamReader/StreamWriter

    if you want to deal with binary data, you can use binary reader/writer like, while, BinaryReader/BinaryWriter.

    Monday, October 22, 2007 1:08 PM
  • File.ReadAllLines is your friend!

     

    string[] lines = System.IO.File.ReadAllLines(@"C:\MyFile.dat");

    foreach (string line in lines)

    {

    if ('0' == line[100])

    {

    line[100] = '1';

    }

    }

     

    In VS 2008, to query over semi-structured data in text files, you can also use LINQ. For example, to create a new file that contains only those lines where line[100] = 0, you would write:

     

    string[] lines = System.IO.File.ReadAllLines(@"C:\MyFile.dat");

    var query = from line in lines

    where line[100] == '0'

    select line;

    System.IO.File.WriteAllLines(@"C:\MyNewFile.dat", query.ToArray());

     

    See http://msdn2.microsoft.com/en-us/library/bb397915(VS.90).aspx for more examples.

                      

    Tuesday, October 23, 2007 6:50 PM