difference between isoFileWriter.Write() and isoFileWriter.WriteLine() - c#

When we use isolated storage in c# we have two functions from isoFileWriter. can someone explain the difference between isoFileWriter.Write() and isoFileWriter.WriteLine()
I am using below code:
IsolatedStorageFile myspace = IsolatedStorageFile.GetUserStoreForApplication();
myspace.CreateDirectory("Emotions");
using (var isoFileStream = new IsolatedStorageFileStream("Emotions\\history.txt", FileMode.OpenOrCreate, myspace))
{
using (var isoFileWriter = new StreamWriter(isoFileStream))
{
isoFileWriter.WriteLine();
}
}

This is StreamWriter.Write and StreamWriter.WriteLine.
The main difference between the two methods is that WriteLine will write a new line to the file, where Write will just write the data (without a new line character).
Calling isoFileWriter.WriteLine() will just write a new line to the file. If you were to call WriteLine while passing a parameter, ie: isoFileWriter.WriteLine("Foo"), it would write Foo followed by a new line. isoFileWriter.Write("Foo"), on the other hand, would just write Foo without the new line character.

Write() vs WriteLine()
That typical of text stream. The difference is WriteLine writes a new line after the text
iso.Write('a');
iso.Write('b');
will output ab
iso.WriteLine('a'); //puts a new line after a
iso.Write('b'); //the next output will be on the same line as b
will output
a
b

The class System.IO.StreamWriter is used to write characters to a stream in a specific encoding. I believe that it is better to use the class StreamWriter to append or write text to a specific file and control the writer (class) later.
Structure
Consider having a StreamWriter called _TextWriter created using the following example
StreamWriter _TextWriter = new StreamWriter(Path)
and another StreamWriter called _TextWriter2 created using the following example
StreamWriter _TextWriter2 = new StreamWriter(Path, true);
If you may notice, our StreamWriter called _TextWriter2 has got two arguments: Path and a boolean true
Using true here simply tells the class that it will be used to APPEND characters to a file that the class may create or already exists. Otherwise, if you leave this blank or insert false the file will be overwritten.
Here's an example
Consider having a file name Path which contains TWO lines with the following content
This is the first line
This is the second line
By using the following code, you'll only have ONE line in your document (Path) which will be Hello
_TextWriter.WriteLine("Hello");
By using the following code, you'll have THREE lines in your document (Path) representing the following content:
This is the first line
This is the second line
Hello
_TextWriter2.WriteLine("Hello");
Now let's move to your question, what is the difference between Write() and WriteLine()
Write() and WriteLine()
The answer is simple, using the method Write() will write characters to the last available line to a specific stream if you have true set up as a boolean for append but will overwrite the content of a specific file if you leave the boolean append blank or set it to false.
Here's an example
Consider the following
You have a file name D:\MyDocument.txt
The file contains the following content
This is my first line
This is my second line
You have the following code :
StreamWriter _TextWriter = new StreamWriter(#"D:\MyDocument.txt");
_TextWriter.Write("Hello");
_TextWriter.Close(); //Save and Close the StreamWriter
What do you expect to happen?
The contents of the file D:\MyDocument.txt will change to the following
Hello
This is because you did not specify whether you want to append or not in the above code and because the default value for append is false, the StreamWriter will not append to the file and thus the file will be overwritten by the new content.
Another Example
Consider the following
You have a file name D:\MyDocument.txt
The file contains the following content
This is my first line
This is my second line
You have the following code :
StreamWriter _TextWriter = new StreamWriter(#"D:\MyDocument.txt", true);
_TextWriter.Write("Hello");
_TextWriter.Close(); //Save and Close the StreamWriter
What do you expect to happen?
The contents of the file D:\MyDocument.txt will change to the following
This is my first line
This is my second lineHello
The file was not overwritten by the word Hello because you have set the boolean append to true but did you notice this? The second line of the file has changed to
This is my first line
This is my second lineHello
This means that Hello was appended to the last line available, this is because you have used Write() which will append the text to the last line available.
Summary
So, if you would not like this to happen, you may use WriteLine() which will create a line at the end of the file first. Then, append or overwrite the file with the characters you specify.

Related

How do I write an array to a text file without overwriting it

This is the code i use to create the text file.
System.IO.File.WriteAllLines(#"C:\Users\****\Desktop\File.txt", array);
How do I append text to an existing file?
The other answers have shown you how to append a single string to a text file. If you naturally have a collection of lines, however, you probably want File.AppendAllLines:
File.AppendAllLines(#"C:\Users\****\Desktop\File.txt", array);
You want File.AppendAllLines:
Appends lines to a file, and then closes the file. If the specified
file does not exist, this method creates a file, writes the specified
lines to the file, and then closes the file.
File.AppendAllLines(#"C:\Users\****\Desktop\Passwords.txt", array);
Like this:
using (StreamWriter sw = File.AppendText(#"C:\Users\****\Desktop\Passwords.txt"))
{
sw.WriteLine(UsernamesAndPass);
}
Ref: https://msdn.microsoft.com/en-us/library/system.io.file.appendtext(v=vs.110).aspx

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 restriction on the amount of text I can write / read with a stream writer / reader in C#?

I am trying to write to some text file using a stream writer.
the text I am trying to write is from a different text file.
I try:
string line = reader.ReadLine(); //reader is a streamReader I defined before
while (line != null)
{
sw.WriteLine(line); //sw is a streamWriter I defined before
line = reader.ReadLine();
}
I also tried:
while (!(reader.EndOfStream))
{
sw.WriteLine(reader.ReadLine()); //sw is a streamWriter I defined before
}
this two methods succeeded to copy the text from the file to the other file, but from some reason not all of the text was copied.
The text file I am trying to copy from is very large, about 96000 lines, and only the ~95000 first lines are copied.
Therfore, I am asking if there is a restriction on the amount of text I can write / read with a stream writer / reader in C#?
Also, I asking for some suggestions for how to succeed copy all the text.
(I read that there is a method copy of the Stream class, but that is for .NET4, so it wont help).
EDIT: I tried to replace the text in the end that didn't copied by a text form the start that was copied. I got the same problem, so it isn't a problem with the characters.
Hmm. Probably you are not flushing your stream. Try doing sw.Autoflush=true; Or, before you close sw, call sw.Flush();
I am going to guess that you are not calling flush on your output stream. This would cause the last few (sometimes a lot) of lines to not be written to the output file.

How to set a string from a text file in C#

I have a text file which always has one line, how could I set a string for the first line of the text file in C#?
e.g. line1 in test.txt = string version
File.WriteAllLines("c:\\test.txt", new[]{"myString"});
To read a textfile with only one line into a variable
var str = File.ReadAllText("c:\\test.txt");
A text file is not line based, so you can't change a specific line in a text file, you would need to rewrite the entire file.
If your file only ever contains that single line, you can just rewrite the file with the new string:
File.WriteAllText(fileName, newValue);
Edit:
As you said that what you actually want to do is to read the file, it's different... If there is only a single line in the file, you can read the entire file:
string line = File.ReadAllText(fileName);
If the file could contain more than a single line, you would have to open the file and only read the first line:
string line;
using (StreamReader reader = new StreamReader(fileName)) {
line = reader.ReadLine();
}
You could also use File.ReadAllLines and get the first line from the result, but that would be wasteful if the file contains a lot of lines.
Have a look at the File class.

Insert data into text file

I want to insert the data at some positions in the text file without actually overwriting on the existing data. I have two text file. "one.txt" file have 1000 lines, "two.txt" file have 10000 lines. I want to read "one.txt" file content and insert into first 1000 lines of "two.txt" file content(Append the content of "one.txt" to the beginning of "two.txt").
Criteria:
Minimum code .
Less Memory consumption(irrespective of programming language )
Performance (will be considered based on size of the file).
just open up a streamreader for the first file, and a stream writer (in append mode) for the second file. As your reading the first 1000 lines from the first file, insert them into the second.
Something like this:
StreamReader sr = new StreamReader("one.txt");
StreamWriter sw = new StreamWriter("two.txt", true); //true for append
index i = 0;
while (i < 1000) {
sw.WriteLine(sr.ReadLine());
i++;
}
You may want to check for end of file on the StreamReader, but this will give you the general idea....
Based on the new information in OP:
You can use this same type of method, but just create a brand new file, reading the data from the first file, followed by the data from the second file. Once it's inside the new file, replace the original "two.txt".
If you're not limited to c# you can just do the following from a windows command line:
copy one.txt + two.txt three.txt
This would create the file you want, but it would be called three.txt. If you must have it in two.txt, you could simply rename two.txt to something else first and then do the copy append with two.txt as the third parm.
If you only have to do this once, here is some code that will do what you want. I did not compile this, but I believe there are no issues.
string[] linesOne = File.ReadAllLines(pathToFile1);
string[] linesTwo = File.ReadAllLines(pathToFile2);
List<string> result = new List<string>();
for(int i=0;i<1000;i++)
{
result.Add(linesOne[i]);
}
result.AddRange(linesTwo);
File.WriteAllLines(pathToFile2, result);
Hope this gets you started.
Bob

Categories