O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Writing Text Files

Our first consideration should always be to “keep it simple,” and use the most convenient method for the job. So, what is the job? We need to create a file, and write some text into it. File.WriteAllText looks like a good place to start.

Writing a Whole Text File at Once

The File class offers three methods that can write an entire file out in a single step: WriteAllBytes, WriteAllLines, and WriteAllText. The first of these works with binary, but our application has text. As you saw in Chapter 10, we could use an Encoding to convert our text into bytes, but the other two methods here will do that for us. (They all use UTF-8.)

WriteAllLines takes a collection of strings, one for each line, but our code in Example 11-19 prepares content in the form of a single string. So as Example 11-20 shows, we use WriteAllText to write the file out with a single line of code. (In fact, we probably didn’t need to bother putting this code into a separate method. However, this will make it easier for us to illustrate some of the alternatives later.)

Example 11-20. Writing a string into a new file

private static void CreateFile(string fullPath, string contents)
{
    File.WriteAllText(fullPath, contents);
}

The path can be either relative or absolute, and the file will be created if it doesn’t already exist, and overwritten if it does.

This was pretty straightforward, but there’s one problem with this technique: it requires us to have the entire file contents ready at the point where we want ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required