I want to write console input Console.ReadLine
to a text file.
It is hard find it anywhere.
Any help is appreciated.
I want to write console input Console.ReadLine
to a text file.
It is hard find it anywhere.
Any help is appreciated.
Since you didn't tell whether the text file already exists or not, you may want-
string path = @"C:\Users\power\Desktop\Tor Browser\test.txt";
if (!File.Exists(path))
{
using FileStream fs = File.Create(path);
}
The code above checks whether file exists or not; if no, creates the file.
If you want append text to file, not overwrite:
string path = @"C:\Users\power\Desktop\Tor Browser\test.txt";
File.AppendAllText(path, "some text");
If you want append text to file in a new line, not overwrite:
string path = @"C:\Users\power\Desktop\Tor Browser\test.txt";
File.AppendAllText(path, Environment.NewLine + "some text");
If you want overwrite the text file:
string path = @"C:\Users\power\Desktop\Tor Browser\test.txt";
File.WriteAllText(path, "some text");
If you have name of the file separated:
string sepratedPath = @"C:\Users\power\Desktop\Tor Browser"
string sepratedFileName = "test.txt";
string path = Path.Combine(sepratedPath, sepratedFileName);
If you want append items of an array line by line:
string path = @"C:\Users\power\Desktop\Tor Browser\test.txt";
string[] lines = { "New line 1", "New line 2" };
File.AppendAllLines(path, lines);
Do not forget using System.IO;
.
My research:
You can try this:
using (System.IO.FileStream fs = new System.IO.FileStream([file-path], System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite))
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(fs))
writer.WriteLine(Console.ReadLine());
thank u,