Jan 15
Here is the code to read a text file from disk one line at a time into a string. This code ensures the file exists and properly closes the file if an exception occurs.
using System;
using System.IO;
namespace CSharp411
{
class Program
{
static void Main( string[] args )
{
string filePath = @"c:\temp\test.txt";
string line;
if (File.Exists( filePath ))
{
StreamReader file = null;
try
{
file = new StreamReader( filePath );
while ((line = file.ReadLine()) != null)
{
Console.WriteLine( line );
}
}
finally
{
if (file != null)
file.Close();
}
}
Console.ReadLine();
}
}
}
Popularity: 43% [?]
Related posts:

thanks
Thank You very much.
It works perfect!
thanks , thanks it really helped me
Thanks….it works….
I need to get the line previous of the current line
there are any way to do this ???
A using() statement on the StreamReader would make this shorter and neater.
hello, i'm a student studying C# because of our final project..can anyone help me please about merging three text files which are from saved points gathered from zedgraph to be separated by comma..
for example
file1.txt contains
1
2
3
file2.txt contains
4
5
6
file3.txt contains
7
8
9
through which i need to have an output of
1 , 4 , 7
2 , 5 , 8
3 , 6 , 9
…thank you in advance.. this is very urgent and important..if you have any codes available..tnx.
@Jovit, here's a code snippet that may do what you want. You'll need to add error-handling, check to ensure the input files are the same length, strip any whitespace, etc. This also wouldn't be the best approach for very large files, but hopefully you get the idea.
string[] lines1 = File.ReadAllLines( "file1.txt" );
string[] lines2 = File.ReadAllLines( "file2.txt" );
string[] lines3 = File.ReadAllLines( "file3.txt" );
StringBuilder sb = new StringBuilder();
int count = lines1.Length;
for (int i = 0; i < count; i++)
{
string line = String.Format( "{0} , {1} , {2}", lines1[i], lines2[i], lines3[i] );
sb.AppendLine( line );
}
File.WriteAllText( "output.txt", sb.ToString() );
I have a CSV file that I open w/ C# via inline = rdr.ReadLine();While (inline != null) wrtr.writeline(blah blah….Wrtr.closeHow can I insert a new column in position number 27?