Replace Text in a TextFile c# - c#

What is the best way to replace text in a text file?
I do not want to give the file a new name
I do not want the text to become one long string which is what happens when I use File.ReadAllText because this is stored as a string and I loose carriage returns etc...
Also, I guess I will run into issues using a StreamReader/StreamWriter because you cannot read and write to the same file?
Thanks

You can do it with a stream opened for both reading and writing:
FileStream fileStream = new FileStream(#"c:\myFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
var streamWriter = new StreamWriter(fileStream);
var streamReader = new StreamReader(fileStream);
...
fileStream .Close();
But the most easy way is still to read all file, edit the text and write it back to the file:
var text = File.ReadAllText(#"c:\myFile.txt");
...
File.WriteAllText(#"c:\myFile.tx", text);

Depending on your file format, you could also read your files line by line (using File.ReadLines) and perform the text replacements for each line.
You can also refer to this answer for a variant based on streams, which is the preferred way if your file is large.
How to read a large (1 GB) txt file in .NET?

Related

What is the correct encoding to read and write PostScript files

I would like to parse a PostScript file, find appropriate line number and insert a PostScript command. So, I need to read the whole file and write it as a new file along with the new commands I want to insert.
I'm using StreamReader and StreamWriter for this process.
StreamReader sr = new StreamReader("filename.ps", System.Text.Encoding.UTF8, true);
StreamWriter sw = new StreamWriter("updatedfilename.ps",true, System.Text.Encoding.UTF8);
When doing this, even though the commands are inserted in the appropriate location, some characters are getting lost due to encoding issues.
For example, please check the below image: In the After content, you can notice the yellow highlighted characters which got added during my write process.
In summary, I would like to know the process to read and write a PS file as it is without losing data because of encoding.

How to read all text from a byte[] file?

I have a text file in the form of a byte[].
I cannot save the file anywhere.
I would like to read all lines/text from this 'file'.
Can anyone point me in the right direction on how I can read all the text from a byte[] in C#?
Thanks!
I would create a MemoryStream and instantiate a StreamReader with that, i.e:
var stream = new StreamReader(new MemoryStream(byteArray));
Then get the text a line at a time with:
stream.readLine();
Or the full file using:
stream.readToEnd();
Another possible solution using Encoding:
Encoding.Default.GetString(byteArray);
It can optionally be split to get the lines:
Encoding.Default.GetString(byteArray).Split('\n');
You can also select a particular encoding like UTF-8 instead of using Default.

writing data to a file with the result is not as expected

I use this code to write a string to a file.
var fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.Write);
var sw = new StreamWriter(fs, Encoding.UTF8);
sw.Write(dataString);
fs.Flush();
sw.Flush();
sw.Close();
When I debug it, I see the dataString correct. However, after writing to a file, there are some strings have wrong orders. Should I add a thread Sleep after writing data to the file because right after writing data to the file, I read it back for other process.
OR probably there is better way to write a string to a file?
Thanks in advance.
OR probably there is better way to write a string to a file?
Yes, there's a simpler way. Use File.WriteAllText or File.AppendAllText.
File.WriteAllText("output.txt", text, Encoding.UTF8);
Apart from being more concise, another advantage is that the file will be correctly closed even if there is an exception. However, I doubt that it will change the order in which the data is written to the file.

C#: Compare text file contents to a string variable

I have an application that dumps text to a text file. I think there might be an issue with the text not containing the proper carriage returns, so I'm in the process of writing a test that will compare the contents of of this file to a string variable that I declare in the code.
Ex:
1) Code creates a text file that contains the text:
This is line 1
This is line 2
This is line 3
2) I have the following string that I want to compare it to:
string testString = "This is line 1\nThis is line 2\nThis is line3"
I understand that I could open a file stream reader and read the text file line by line and store that in a mutable string variable while appending "\n" after each line, but wondering if this is re-inventing the wheel (other words, .NET has a built in class for something like this). Thanks in advance.
you can either use StreamReader's ReadToEnd() method to read contents in a single string like
using System.IO;
using(StreamReader streamReader = new StreamReader(filePath))
{
string text = streamReader.ReadToEnd();
}
Note: you have to make sure that you release the resources (above code uses "using" to do that) and ReadToEnd() method assumes that stream knows when it has reached an end. For interactive protocols in which the server sends data only when you ask for it and does not close the connection, ReadToEnd might block indefinitely because it does not reach an end, and should be avoided and also you should take care that current position in the string should be at the start.
You can also use ReadAllText like
// Open the file to read from.
string readText = File.ReadAllText(path);
which is simple it opens a file, reads all lines and takes care of closing as well.
No, there is nothing built in for this. The easiest way, assuming that your file is small, is to just read the whole thing and compare them:
var fileContents = File.ReadAllText(fileName);
return testString == filecontents;
If the file is fairly long, you may want to compare the file line by line, since finding a difference early on would allow you to reduce IO.
A faster way to implement reading all the text in a file is
System.IO.File.ReadAllText()
but theres no way to do the string level comparison shorter
if(System.IO.File.ReadAllText(filename) == "This is line 1\nThis is line 2\nThis is line3") {
// it matches
}
This should work:
StreamReader streamReader = new StreamReader(filePath);
string originalString = streamReader.ReadToEnd();
streamReader.Close();
I don't think there is a quicker way of doing it in C#.
You can read the entire file into a string variable this way:
FileStream stream;
StreamReader reader;
stream = new FileStream(yourFileName, FileMode.Open, FileAccess.Read, FileShare.Read);
reader = new StreamReader(stream);
string stringContainingFilesContent = reader.ReadToEnd();
// and check for your condition
if (testString.Equals(stringContainingFilesContent, StringComparison.OrdinalIgnoreCase))

Is there a way to read large text file in parts?

I have a large file(60mb) and I am reading the file into a string and Iam returning that string to another method.
Now when I am reading the file into a string its giving System out of memory exception.
Is there a way to read file in parts and append it to the string?
If not is there a way around this?
static public string Serialize()
{
string returnValue;
System.IO.FileInfo file1 = new FileInfo(#"c:\file.txt");
returnValue = System.IO.File.ReadAllText(file1.ToString());
}
How do you read the file right now ?
You could use the StreamReader class, and read the file line by line (ReadLine method).
You could also read a specified amount of bytes from the file on each read operation (Read method)
Yes- it's called streaming. Have a look at the StreamReader Class. Though I'm not sure why you want 1 60MB in one string. Probably best to deal with it a little at a time if possible (possibly in your scenario on a line by line basis?).
Instead of ReadAllText look at OpenRead and passing the returned FileStream into the constructor of a StreamReader, have a look at doing something along these lines if possible:
using (FileStream fs = File.OpenRead("c:\theFile.text"))
using (StreamReader sr = new StreamReader(fs))
{
string oneLine = sr.ReadLine();
}
even if you read it line by line (or in parts by streaming), you will run out of memory as you are appending it to a single string. is compressing it along the way an option? if not, i'd probably up the maxHeap for the JVM to 512MB or similar.

Categories