How to set a string from a text file in C# - 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.

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

Handling Special Characters (¦)

I'm a bit lost on how to read and write to/from text files in C# when special characters are present. I'm writing a simple script that does some cleanup on a .txt data file which contains the '¦' character as its delimiter.
foreach (string file in Directory.EnumerateFiles(#"path\raw txt","*.txt"))
{
string contents = File.ReadAllText(file);
contents = contents.Replace("¦", ",");
File.WriteAllText(file.Replace("raw txt", "txt"), contents);
}
However, when I open the txt file in Notepad++, the delimeter is now �. What exactly is going on? What even is this characters (¦) encoding / how would I determine that? I've tried adding things like:
string contents = File.ReadAllText(file, Encoding.UTF8);
File.WriteAllText(file.Replace("raw txt", "txt"), contents, Encoding.UTF8);
Everything is now working correctly by switching the encoding to 'default' when both reading/writing.
string contents = File.ReadAllText(file, Encoding.Default);
File.WriteAllText(file.Replace("raw txt", "txt"), contents, Encoding.Default);
Try change encoding of Notepad to UTF-8

difference between isoFileWriter.Write() and isoFileWriter.WriteLine()

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.

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))

append text to lines in a CSV file

This question seems to have been asked a million times around the web, but I cannot find an answer which will work for me.
Basically, I have a CSV file which has a number of columns (say two). The program goes through each row in the CSV file, taking the first column value, then asks the user for the value to be placed in the second column. This is done on a handheld running Windows 6. I am developing using C#.
It seems a simple thing to do. But I cant seem to add text to a line.
I cant use OleDb, as System.Data.Oledb isnt in the .Net version I am using. I could use another CSV file, and when they complete each line, it writes it to another CSV file. But the problems with that are - The file thats produced at the end needs to contain EVERY line (so what if they pull the batterys out half way). And what if they go back, to continue doing this another time, how will the program know where to start back from.
For every row, open the output file, append the new row to it, and then close the output file. To restart, count the number of rows in the existing output file from the previous run, which will give you your starting in the input file (i.e., skip that number of rows in the input file).
Edit: right at the start, use System.IO.File.Copy to copy the input file to the output file, so you have all the file in case of failure. Now open the input file, read a line, convert it, use File.ReadAllLines to read ALL of the output file into an array, replace the line you have changed at the right index in the array, then use File.WriteAllLines to write out the new output file.
Something like this:
string inputFileName = ""; // Use a sensible file name.
string outputFileName = ""; // Use a sensible file name.
File.Copy(inputFileName, outputFileName, true);
using (StreamReader reader = new StreamReader(inputFileName))
{
string line = null;
int inputLinesIndex = 0;
while ((line = reader.ReadLine()) != null)
{
string convertedLine = ConvertLine(line);
string[] outputFileLines = File.ReadAllLines(outputFileName);
if (inputLinesIndex < outputFileLines.Length)
{
outputFileLines[inputLinesIndex] = convertedLine;
File.WriteAllLines(outputFileName, outputFileLines);
}
inputLinesIndex++;
}
}

Categories