This article is currently in the process of being translated into Czech (~18% done).
Reading and writing files
V této kapitole se podíváme na čtení a psaní jednoduchých souborů s C#. Naštěstí pro nás to C# dělá velmi snadné. Třída Soubor z oboru názvů Syste.IO přichází s téměř vším, co bychom mohli chtít, takže je snadné dělat jednoduché čtení a psaní souboru.
V našem prvním příkladu vytvoříme extrémně minimalistický textový editor. Ve skutečnosti je to tak jednoduché, že můžeme číst pouze jeden soubor a pak do něj psát nový obsah a pouze jediný řádek textu najednou. Ale ukazuje, jak snadné je použít třídu File:
using System;
using System.IO;
namespace FileHandlingArticleApp
{
class Program
{
static void Main(string[] args)
{
if(File.Exists("test.txt"))
{
string content = File.ReadAllText("test.txt");
Console.WriteLine("Current content of file:");
Console.WriteLine(content);
}
Console.WriteLine("Please enter new content for the file:");
string newContent = Console.ReadLine();
File.WriteAllText("test.txt", newContent);
}
}
}
You will notice that we use the File class in three places: We use it to check if our file exists, we use the ReadAllText() method to read the content of the file, and we use the WriteAllText() method to write new content to the file. You will notice that I'm not using absolute paths, but just a simple filename. This will place the file in the same directory as the executable file, which is fine for now. Other than that, the example should be easy enough to understand: We check for the file, if it exists, we read its content and output it to the console. Then we prompt the user for new content, and once we have it, we write it to the file. Obviously that will overwrite the previous content, but for now, that's just fine. We could however use the AppendAllText method instead. Try changing the WriteAllText line to this instead:
File.AppendAllText("test.txt", newContent);
If you run it, you will see that the new text is added to the existing text instead of overwriting it. As simple as that. But we still get only one line of text per execution of our application. Let's be a bit creative and change that. Replace the last lines in our example with this:
Console.WriteLine("Please enter new content for the file - type exit and press enter to finish editing:");
string newContent = Console.ReadLine();
while(newContent != "exit")
{
File.AppendAllText("test.txt", newContent + Environment.NewLine);
newContent = Console.ReadLine();
}
As you can see, we instruct the user to enter the word exit when they wish to stop editing the file, and until they do just that, we append the user input to the file and then prompt for a new line. We also append a newline character, the Environment.NewLine, to make it look like actual lines of text.
However, instead of writing to the file each time, a more pretty solution would probably look something like this:
Console.WriteLine("Please enter new content for the file - type exit and press enter to finish editing:");
using(StreamWriter sw = new StreamWriter("test.txt"))
{
string newContent = Console.ReadLine();
while(newContent != "exit")
{
sw.Write(newContent + Environment.NewLine);
newContent = Console.ReadLine();
}
}
The usage of Streams is a bit out of the scope of this chapter, but the cool thing about it in this example is that we only open the file once, and then write the changes to it once we're satisfied. In this case, we're taking advantage of the using() statement of C#, which ensures that the file reference is closed once it goes out of scope, which is when it's block of { } is done. If you don't use the using() statement, you will have to manually call the Close() method on the StreamWriter instance.