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");
Related
I was looking to append text to a exact location in a text file. I have used StreamReader to find the text in the file I am looking for. I thought about using StreamWriter but that obviously doesn't make sense. I was hoping to find some "append" method in some class somewhere that would help me do this but with now success. Or is there a better way to do this than to use StreamReader?
using (StreamReader sr = new StreamReader(fileName))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("VAR_GLOBAL CONSTANT"))
{
//append text before this variable
// e.g. (*VAR_GLOBAL CONSTANT
// append the (* before VAR_GLOBAL CONSTANT
}
if (line.Contains("END_VAR"))
{
//append text after this variable
// e.g. END_VAR*)
// append the *) after END_VAR
}
}
}
Does anyone have any thoughts on how to accomplish this?
One way to do it would be to read the file contents into a string, update the contents locally, and then write it back to the file again. This probably isn't very feasible for really large files, especially if the appending is done at the end, but it's a start:
var filePath = #"f:\public\temp\temp.txt";
var appendBeforeDelim = "VAR_GLOBAL CONSTANT";
var appendAfterDelim = "END_VAR";
var appendBeforeText = "Append this string before some text";
var appendAfterText = "Append this string after some text";
var newFileContents = File.ReadAllText(filePath)
.Replace(appendBeforeDelim, $"{appendBeforeText}{appendBeforeDelim}")
.Replace(appendAfterDelim, $"{appendAfterDelim}{appendAfterText}");
File.WriteAllText(filePath, newFileContents);
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
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);
}
}
I'm importing an .sql file that I created with SQLExplorer into my .NET program using StreamReader (which will eventually be passed through OdbcConnection, fyi.) The problem is that when I use the ReadToEnd() method it not only imports the SQL itself, but it imports all of the formatting. So the string is littered with \r and \t and the like.
I've been looking at both using split or possibly regex to break the string down and remove the unwanted bits and pieces. But before throwing a bunch of effort into that I wondered if there was perhaps something I'm missing in the StreamReader class? Is there a way to tell it to just ignore the formatting characters?
Here's the code I have right now:
public static Object SQLQueryFileCall(String SQLQueryFileName){
string SQLQuery = "";
string directory = System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location);
SQLQueryFileName = directory + "\\" + SQLQueryFileName;
//read in the file and pass to ODBC, return a Object[] of whatever comes back...
try{
using (StreamReader myStreamReader = new StreamReader(SQLQueryFileName)) {
SQLQuery = myStreamReader.ReadToEnd();
Console.WriteLine(SQLQuery);
}
}
catch (Exception e){
//Find the error
Console.WriteLine("File could not be read:");
string error = e.Message;
MessageBox.Show(error);
return null;
}
}
Feel free to offer any advice you might have on the code, seeing as I'm pretty new.
But yeah, mostly I'm just hoping there's a method in the StreamReader class that I'm just not understanding. I've gone to Microsoft's online documentation, and I feel I've given it a good look, but then again, I'm new and perhaps the concept skipped over my head?
Any help?
NOTE: There are multiple \t that are in the middle of some of the lines, and they do need to be removed. Hence using trim would...be tricky at least.
Well, myStreamReader.ReadToEnd(); will get you everything. The easiest way to get rid of most unneeded whitespace is to read it line-by-line and then simply .Trim() every line.
using (StreamReader myStreamReader = new StreamReader(SQLQueryFileName))
{
string line;
List<string> lines = new List<string();
while ((line = myStreamReader.ReadLine()) != null)
lines.Add(line.Trim());
SQLQuery = string.Join("\n", lines);
Console.WriteLine(SQLQuery);
}
SQL, by definition, shouldn't have a problem with whitespaces like tabs and newlines throughout code. Verify that your actual SQL is correct first.
Also, blindly stripping whitespace could potentially have an impact on textual data contained within your script; what happens if you have a string literal that contains a tab character?
using (StreamReader myStreamReader = new StreamReader(SQLQueryFileName))
{
while ((line = myStreamReader.ReadLine()) != null)
{
Console.WriteLine(line.Trim().Replace(#"\t"," ")
}
}
If it is a display and not content issue I think you could use WPF and a RichTextBox.
SQLQuery = Regex.Replace(SQLQuery, #"\t|\n|\r", "");
Better to use as you could remove content of SQL insertions:
using (StreamReader reader = new StreamReader(fileName))
{
String line;
List<string> lines = new List<string();
while ((line = myStreamReader.ReadLine()) != null)
SQLQuery += line.Trim() + "\n";
}
This is what helped me in 2020, incase if someone is looking for this
using (StreamReader sr = new StreamReader(stream))
{
return Regex.Replace(sr.ReadToEnd().Trim(), #"\s", "");
}
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.