There are a lot of different ways to read and write files (text files, not binary) in C#.
I just need something that is easy and uses the least amount of code, because I am going to be working with files a lot in my project. I only need something for string since all I need is to read and write strings.
Use File.ReadAllText and File.WriteAllText.
MSDN example excerpt:
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
...
// Open the file to read from.
string readText = File.ReadAllText(path);
In addition to File.ReadAllText, File.ReadAllLines, and File.WriteAllText (and similar helpers from File class) shown in another answer you can use StreamWriter/StreamReader classes.
Writing a text file:
using(StreamWriter writetext = new StreamWriter("write.txt"))
{
writetext.WriteLine("writing in text file");
}
Reading a text file:
using(StreamReader readtext = new StreamReader("readme.txt"))
{
string readText = readtext.ReadLine();
}
Notes:
You can use readtext.Dispose() instead of using, but it will not close file/reader/writer in case of exceptions
Be aware that relative path is relative to current working directory. You may want to use/construct absolute path.
Missing using/Close is very common reason of "why data is not written to file".
FileStream fs = new FileStream(txtSourcePath.Text,FileMode.Open, FileAccess.Read);
using(StreamReader sr = new StreamReader(fs))
{
using (StreamWriter sw = new StreamWriter(Destination))
{
sw.Writeline("Your text");
}
}
The easiest way to read from a file and write to a file:
//Read from a file
string something = File.ReadAllText("C:\\Rfile.txt");
//Write to a file
using (StreamWriter writer = new StreamWriter("Wfile.txt"))
{
writer.WriteLine(something);
}
using (var file = File.Create("pricequote.txt"))
{
...........
}
using (var file = File.OpenRead("pricequote.txt"))
{
..........
}
Simple, easy and also disposes/cleans up the object once you are done with it.
#AlexeiLevenkov pointed me at another "easiest way" namely the extension method. It takes just a little coding, then provides the absolute easiest way to read/write, plus it offers the flexibility to create variations according to your personal needs. Here is a complete example:
This defines the extension method on the string type. Note that the only thing that really matters is the function argument with extra keyword this, that makes it refer to the object that the method is attached to. The class name does not matter; the class and method must be declared static.
using System.IO;//File, Directory, Path
namespace Lib
{
/// <summary>
/// Handy string methods
/// </summary>
public static class Strings
{
/// <summary>
/// Extension method to write the string Str to a file
/// </summary>
/// <param name="Str"></param>
/// <param name="Filename"></param>
public static void WriteToFile(this string Str, string Filename)
{
File.WriteAllText(Filename, Str);
return;
}
// of course you could add other useful string methods...
}//end class
}//end ns
This is how to use the string extension method, note that it refers automagically to the class Strings:
using Lib;//(extension) method(s) for string
namespace ConsoleApp_Sandbox
{
class Program
{
static void Main(string[] args)
{
"Hello World!".WriteToFile(#"c:\temp\helloworld.txt");
return;
}
}//end class
}//end ns
I would never have found this myself, but it works great, so I wanted to share this. Have fun!
These are the best and most commonly used methods for writing to and reading from files:
using System.IO;
File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file
File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it.
File.ReadAllText(sFilePathAndName);
The old way, which I was taught in college was to use stream reader/stream writer, but the File I/O methods are less clunky and require fewer lines of code. You can type in "File." in your IDE (make sure you include the System.IO import statement) and see all the methods available. Below are example methods for reading/writing strings to/from text files (.txt.) using a Windows Forms App.
Append text to an existing file:
private void AppendTextToExistingFile_Click(object sender, EventArgs e)
{
string sTextToAppend = txtMainUserInput.Text;
//first, check to make sure that the user entered something in the text box.
if (sTextToAppend == "" || sTextToAppend == null)
{MessageBox.Show("You did not enter any text. Please try again");}
else
{
string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a path\filename.txt as string.
if (sFilePathAndName == "" || sFilePathAndName == null)
{
//MessageBox.Show("You cancalled"); //DO NOTHING
}
else
{
sTextToAppend = ("\r\n" + sTextToAppend);//create a new line for the new text
File.AppendAllText(sFilePathAndName, sTextToAppend);
string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\\') + 1);
MessageBox.Show("Your new text has been appended to " + sFileNameOnly);
}//end nested if/else
}//end if/else
}//end method AppendTextToExistingFile_Click
Get file name from the user via file explorer/open file dialog (you will need this to select existing files).
private string getFileNameFromUser()//returns file path\name
{
string sFileNameAndPath = "";
OpenFileDialog fd = new OpenFileDialog();
fd.Title = "Select file";
fd.Filter = "TXT files|*.txt";
fd.InitialDirectory = Environment.CurrentDirectory;
if (fd.ShowDialog() == DialogResult.OK)
{
sFileNameAndPath = (fd.FileName.ToString());
}
return sFileNameAndPath;
}//end method getFileNameFromUser
Get text from an existing file:
private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
string sFileNameAndPath = getFileNameFromUser();
txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}
Or, if you are really about lines:
System.IO.File also contains a static method WriteAllLines, so you could do:
IList<string> myLines = new List<string>()
{
"line1",
"line2",
"line3",
};
File.WriteAllLines("./foo", myLines);
It's good when reading to use the OpenFileDialog control to browse to any file you want to read. Find the code below:
Don't forget to add the following using statement to read files: using System.IO;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = File.ReadAllText(openFileDialog1.FileName);
}
}
To write files you can use the method File.WriteAllText.
class Program
{
public static void Main()
{
//To write in a txt file
File.WriteAllText("C:\\Users\\HP\\Desktop\\c#file.txt", "Hello and Welcome");
//To Read from a txt file & print on console
string copyTxt = File.ReadAllText("C:\\Users\\HP\\Desktop\\c#file.txt");
Console.Out.WriteLine("{0}",copyTxt);
}
}
private void Form1_Load(object sender, EventArgs e)
{
//Write a file
string text = "The text inside the file.";
System.IO.File.WriteAllText("file_name.txt", text);
//Read a file
string read = System.IO.File.ReadAllText("file_name.txt");
MessageBox.Show(read); //Display text in the file
}
Reading from file
string filePath = #"YOUR PATH";
List<string> lines = File.ReadAllLines(filePath).ToList();
Writing to file
List<string> lines = new List<string>();
string a = "Something to be written"
lines.Add(a);
File.WriteAllLines(filePath, lines);
Simply:
String inputText = "Hello World!";
File.WriteAllText("yourfile.ext",inputText); //writing
var outputText = File.ReadAllText("yourfile.ext"); //reading
You're looking for the File, StreamWriter, and StreamReader classes.
I created a console application which accepts arguments. After building the program i will run it through cmd in which the user will input like this "filemgr.exe create [filename] [contents]" . My code is below. I want to enter "my text here" content, but when i check the output, only the FIRST word is displayed which is the "my", how to include the rest of the strings?(which is the text here)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace filemgr
{
class Program
{
static void Main(string[] args)
{
if (args[0]=="create")
{
using (StreamWriter file = new StreamWriter(args[1]))
{
file.Write(args[2]);
}
}
}
}
}
You need to recombine the args array into a string (although this method will likely lose quotes):
file.Write(string.Join(" ", args.Skip(2)));
Alternatively you can quote the string in the commandline:
program.exe create test.txt "hello this is a message"
Also, if you want to append to the file through sequential calls you need to open the stream like so:
using (StreamWriter file = new StreamWriter(args[1], true))
This signifies that you want append mode, and not create/replace.
Pass content args in double quotes
filemgr.exe create [filename] "[contents]"
filemgr.exe create C:\test.txt "my file content"
I would suggest to use quotes even in file path as well. When you use args, its always a chance to make mistake while accessing arguments.
Finally got my code working fine, but I need to extract the most recent zipped file within the directory.
Really not sure how to go about this, can someone please point me in the correct direction, was thinking of using modified date and time, please see my code below...
using System;
using System.IO;
using System.IO.Compression;
namespace unZipMe
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo file = new DirectoryInfo(#"c:\Temp\ZipSampleExtract");
if(file.Exists)
{
file.Delete(true);
}
string myDir = (#"c:\Temp\ZipSampleExtract");
bool exists = System.IO.Directory.Exists(myDir);
if (!exists)
{
System.IO.Directory.CreateDirectory(myDir);
}
//provide the folder to be zipped
//string folderToZip = #"c:\Temp\ZipSample";
//provide the path and name for the zip file to create
string zipFile = #"c:\Temp\ZipSampleOutput\MyZippedDocuments.zip";
//call the ZipFile.CreateFromDirectory() method
//ZipFile.CreateFromDirectory(folderToZip, zipFile, CompressionLevel.Optimal, false);
//specif the directory to which to extract the zip file
string extractFolder = #"c:\Temp\ZipSampleExtract\";
//call the ZipFile.ExtractToDirectory() method
ZipFile.ExtractToDirectory(zipFile, extractFolder);
}
}
}
While learning with books sometimes i copy some code from pdf, to test it.
This tiny exe was suppose to change ‘ ’ “ ” to ' or "
and it work fine, but only if tested *.cs file is opened manually before I debug my methods.
Otherwise it's not working. When code paste into concerned file directly, and closed, without opening once again The Replace method return "Unexpected character ?"
I dont understand the probleme, since File.ReadAllText already open and close the file.
using System;
using System.Collections.Generic;
using System.IO;
class Test
{
public static void Main()
{
string path = Directory.GetCurrentDirectory();
string[] csfiles = Directory.GetFiles(path, "*.cs");
foreach (var item in csfiles)
{
string text = File.ReadAllText(item);
text = text.Replace("‘", "\'")
.Replace("’", "\'")
.Replace("“", "\"")
.Replace("”", "\"");
File.WriteAllText(item, text);
}
}
}
Apparently File.ReadAllText(); does change encoding when opening.
My caracters (being in ASCII+ANSI) was ruined just when opened.
string text = File.ReadAllText(path, Encoding.Default); keeps original encoding when opening. Replace work fine on this, and so my exe.
:) Thank you for your help!
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = Directory.GetCurrentDirectory();
string[] csfiles = Directory.GetFiles(path, "*.cs");
foreach (var item in csfiles)
{
string text = File.ReadAllText(item, Encoding.Default);
string newtext = text.Replace("‘", "\'")
.Replace("’", "\'")
.Replace("“", "\"")
.Replace("”", "\"");
File.WriteAllText(item, newtext);
}
}
}
How to read an ANSI encoded file containing special characters
I have a problem with System.IO.Path.GetFileNameWithoutExtension. If i load a file, the string which is returned by the method contains some hidden chars. In HEX: 3F.
The follwing pictures contains the problem. See the hex editor:
The texfiles were created with Notepad++ and the Encoding is UTF-8 without BOM.
Maybe some one has a solution, thank you!
I created file with Notepad++ v6.6.4 and put the file in debug folder called myFile.txt and the Encoding is "UTF-8 without BOM" and if you apply the next code which read all the text from the original file created above and put all the content in new file in the same directory you will find exactly all the content without any difference.
using System;
using System.IO;
namespace FilePathWithNotepad__
{
class Program
{
static void Main(string[] args)
{
string originalFilePath = Environment.CurrentDirectory + "\\myFile.txt";
string title = Path.GetFileNameWithoutExtension(originalFilePath);
string content = File.ReadAllText(originalFilePath);
string newfile = Path.GetFileName(Environment.CurrentDirectory + "\\new.txt");
File.WriteAllText(newfile,content);
}
}
}