I have a list box that will display some info from a txt file. However, I can't seem to print out the info on different lines. Here's the snippet. The text should be displayed when user presses a button.
using (StreamReader sr = new StreamReader("Books.txt"))
{
String line = sr.ReadToEnd();
listBox1.Items.Add(line + "\n");
}
There are 10 lines in the file.
You can use File.ReadAllLines documented at http://msdn.microsoft.com/en-us/library/system.io.file.readalllines.aspx.
Example of usage is provided at http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx
In your example:
var lines = File.ReadAllLines("Book.txt");
foreach (var element in lines)
{
listBox1.Items.Add(element);
}
You can also do one liner.
listBox1.Items.AddRange(File.ReadAllLines("Book.txt")); // tinstaafl's comment
ReadToEnd() reads everything in the file into one variable.
What you want is ReadLine().
This is one way that should work (though it can probably be done better).
using (StreamReader sr = new StreamReader("Books.txt"))
{
while(true)
{
String line = sr.ReadLine();
if(line==null)
break;
listBox1.Items.Add(line + "\n");
}
}
See the documentation for StreamReader.
By using StreamReader.ReadToEnd() you are putting the whole content of the file in a single string.
To add a Item to the ListBox for each line in the file this should work:
using (StreamReader sr = new StreamReader("Books.txt"))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
listBox1.Items.Add(line);
}
}
Related
I have a text file sent from others. If I open in NotePad++ and view all the symbols, I can see both {LF} and {CRLF} work as line separator.
Example:
line1: ABC {CRLF}
line2: XYZ {LF}
Question: If I want to replace {CRLF} with {LF} and write to a new file, why the output text file cannot show separate line and the separator symbols disappear. Write just writes the line and append another line without start a new line, but the line still has {LF} in it, hasn't it? Is that because I am working in Windows system? But how the original file with both {LF} and {CR}{LF} can be viewed as two separate lines?
Code is very simple:
using (StreamReader sr = new StreamReader(#"\\...\TEST.txt"))
{
using (StreamWriter sw = new StreamWriter(#"\\...\TEST2.txt"))
{
string line = "";
while ((line = sr.ReadLine()) != null)
{
sw.Write(line.Replace("\r\n", "\n"));
}
}
}
When you use ReadLine() you're trimming the EOL characters (CR and LF). Instead you should do one of the following ways:
string file1 = #"\\...\TEST.txt";
string file2 = #"\\...\TEST2.txt";
using (StreamReader sr = new StreamReader(file1))
{
using (StreamWriter sw = new StreamWriter(file2))
{
string text = sr.ReadToEnd();
sw.Write(text.Replace("\r\n", "\n"));
}
}
Or
File.WriteAllText(file2,File.ReadAllText(file1).Replace("\r\n", "\n"));
But only if your file is not too big. Otherwise, Jim solution is the way to go.
Your code doesn't work because when you call sr.Readline(), the returned string does not contain the CRLF characters. Those characters are added by WriteLine, which is essentially Write(s + Environment.NewLine).
To make your code work, change it to
while ((line = sr.ReadLine()) != null)
{
sw.Write(line + "\n");
}
You can simplify your code with:
File.WriteAllLines("outputFileName",
FileReadLines("inputFileName").Select(s => s + "\n");
I have a small winform app with a button, which, when clicked, I want to search a text file (file.txt) for a specific word and replace the entire line on which it was found by something else.
Let's say my text file is:
ohad yes no
box cat dog
etc...
I want to search for ohad and once find it replace the line "ohad yes no" to new line "yes I did it"
so the txt file will be:
yes I did it
box cat dog
etc...
This is my code so far:
string lineX;
StringBuilder sb = new StringBuilder();
using (System.IO.StreamReader file = new System.IO.StreamReader(textBox20.Text))
{
while ((lineX = file.ReadLine()) != null)
{
if (lineX.Contains("SRV"))
{
sb.AppendLine(lineX.ToString());
}
}
}
StreamReader streamReader;
streamReader = File.OpenText(textBox20.Text);
string contents = streamReader.ReadToEnd();
streamReader.Close();
StreamWriter streamWriter = File.CreateText(textBox20.Text);
streamWriter.Write(contents.Replace(sb.ToString(), textBox26.Text + textBox29.Text + textBox30.Text + textBox27.Text + textBox28.Text));
streamWriter.Close();
Thanks you all in advance
Ohad
Try this:
// Read file into a string array (NOTE: You should check if exists first!)
string[] Lines = File.ReadAllLines(textBox20.Text);
for(int i=0;i<Lines.Length;i++) {
if(Lines[i].Contains("SRV")) {
Lines[i] = "New value for line";
// if you only want to replace one line, uncomment the next row:
// break;
}
}
// Write array back to file
File.WriteAllLines(textBox20.Text, Lines);
for a starter, how about following these comments i put together.
var s = #"
ohad yes no
box cat dog
";
//split string into array
//go through each item in array
//check if it contains "ohad"
//if so, replace that line with my text
//convert array to string
Pretty simple one I hope. I have an article of text that I want to display in a window. Now rather than have this massive load of text in the centre of my code, can I add it as a Resource and read it out to the window somehow?
For those asking why, it's simply because it is a massive article and would be very ugly looking stuck in the middle of my code.
UPDATE FOR H.B.
I have tried a number of different approaches to this and am currently looking into the GetManifestResourceStream and using an embeddedResource (txt file) and writing that out to screen. Haven't finished testing it yet but if it works it would be a heck of a lot nicer than copying and pasting the entire text txtbox1.Text = "...blah blah blah".
_textStreamReader = new
StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Problem.Explaination.txt"));
try
{
if (_textStreamReader.Peek() != -1)
{
txtBlock.Text = _textStreamReader.ReadLine();
}
}
catch
{
MessageBox.Show("Error writing text!");
}
My query remains, is there a better way of achieving this (assuming this is even successful)
Thanks
NOTE
In my example above I only want one line of text. If you were adapting this to read a number of lines from a file you would change it like so;
StreamReader _textStreamReader;
_textStreamReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Problem.Explaination.txt"));
var fileContents = _textStreamReader.ReadToEnd();
_textStreamReader.Close();
String[] lines = fileContents.Split("\n"[0]);
String[] lines2;
Int16 count;
foreach (string line in lines)
{
txtBlock.Text += line;
}
Add the file as a resource and, in your code, load it into a string.
StringBuilder sb = new StringBuilder();
using (var stream = this.GetType().Assembly.GetManifestResourceStream("MyNamespace.TextFile.txt"))
using(var reader = new StreamReader(stream))
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.AppendLine(line);
}
}
ViewModel.Text = sb.ToString();
You could place that text in a text file, and read it out in code
http://msdn.microsoft.com/en-us/library/db5x7c0d.aspx
I can currently remove the last line of a text file using:
var lines = System.IO.File.ReadAllLines("test.txt");
System.IO.File.WriteAllLines("test.txt", lines.Take(lines.Length - 1).ToArray());
Although, how is it possible to instead remove the beginning of the text file?
Instead of lines.Take, you can use lines.Skip, like:
var lines = File.ReadAllLines("test.txt");
File.WriteAllLines("test.txt", lines.Skip(1).ToArray());
to truncate at the beginning despite the fact that the technique used (read all text and write everything back) is very inefficient.
About the efficient way: The inefficiency comes from the necessity to read the whole file into memory. The other way around could easily be to seek in a stream and copy the stream to another output file, delete the original, and rename the old. That one would be equally fast and yet consume much less memory.
Truncating a file at the end is much easier. You can just find the trunaction position and call FileStream.SetLength().
Here is an alternative:
using (var stream = File.OpenRead("C:\\yourfile"))
{
var items = new LinkedList<string>();
using (var reader = new StreamReader(stream))
{
reader.ReadLine(); // skip one line
string line;
while ((line = reader.ReadLine()) != null)
{
//it's far better to do the actual processing here
items.AddLast(line);
}
}
}
Update
If you need an IEnumerable<string> and don't want to waste memory you could do something like this:
public static IEnumerable<string> GetFileLines(string filename)
{
using (var stream = File.OpenRead(filename))
{
using (var reader = new StreamReader(stream))
{
reader.ReadLine(); // skip one line
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
}
static void Main(string[] args)
{
foreach (var line in GetFileLines("C:\\yourfile.txt"))
{
// do something with the line here.
}
}
var lines = System.IO.File.ReadAllLines("test.txt");
System.IO.File.WriteAllLines("test.txt", lines.Skip(1).ToArray());
Skip eliminates the given number of elements from the beginning of the sequence. Take eliminates all but the given number of elements from the end of the sequence.
To remove fist line from a text file
System.IO.StreamReader file = new System.IO.StreamReader(filePath);
string data = file.ReadToEnd();
file.Close();
data = Regex.Replace(data, "<.*\n", "");
System.IO.StreamWriter file = new System.IO.StreamWriter(filePath, false);
file.Write(data);
file.Close();
can do in one line also
File.WriteAllLines(origialFilePath,File.ReadAllLines(originalFilePath).Skip(1));
Assuming you are passing your filePath as parameter to the function.
Notepad:
Hello world!
How I'll put it in C# and convert it into string..?
So far, I'm getting the path of the notepad.
string notepad = #"c:\oasis\B1.text"; //this must be Hello world
Please advice me.. I'm not familiar on this.. tnx
You can read text using the File.ReadAllText() method:
public static void Main()
{
string path = #"c:\oasis\B1.txt";
try {
// Open the file to read from.
string readText = System.IO.File.ReadAllText(path);
Console.WriteLine(readText);
}
catch (System.IO.FileNotFoundException fnfe) {
// Handle file not found.
}
}
You need to read the content of the file, e.g.:
using (var reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read))
{
return reader.ReadToEnd();
}
Or, as simply as possible:
return File.ReadAllText(path);
make use of StreamReader and read the file as shown below
string notepad = #"c:\oasis\B1.text";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(notepad))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
}
string s = sb.ToString();
Use File.ReadAllText
string text_in_file = File.ReadAllText(notepad);
check this example:
// Read the file as one string.
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
// Display the file contents.
Console.WriteLine(myString);
// Suspend the screen.
Console.ReadLine();
Reading From a Text File (Visual C#), in this example # is not used when StreamReader is being called, however when you write the code in Visual Studio it will give the below error for each \
Unrecognized escape sequence
To escape this error you can write # before " that is at the beginning of your path string.
I shoul also mentioned that it does not give this error if we use \\ even if we do not write #.
// Read the file as one string.
System.IO.StreamReader myFile = new System.IO.StreamReader(#"c:\oasis\B1.text");
string myString = myFile.ReadToEnd();
myFile.Close();
// Display the file contents.
Console.WriteLine(myString);
// Suspend the screen.
Console.ReadLine();