C# Simplified, part 5: Error Handling and Files - Creating files
(Page 6 of 8 )
With C#, you can create new files with the help of the Create() method of the FileInfo class. You can also access specific information about the file. You can even delete a file. In listing 5.8, a file named Mycsharp.txt is created on the D drive of your system. After creating the file, the program displays some useful properties.
Listing 5.8
using System;
using System.IO;
class CreateFile
{
public static void Main()
{
FileInfo finfo = new FileInfo(@"D:\Mycsharp.txt");
FileStream fstream = finfo.Create();
Console.WriteLine("File Mycsharp.txt created");
Console.WriteLine("Creation Time: {0}",finfo.CreationTime);
Console.WriteLine("Full Name: {0}",finfo.FullName);
Console.WriteLine("FileAttributes: {0}",finfo.Attributes.ToString());
fstream.Close();
}
}
You can verify the existence of the file by going to the D drive using My Computer or Windows Explorer.
Listing 5.9 is a continuation of listing 5.8. After creating the file, the program will ask you to press any key to delete the file. If you press a key the file system will close, and the created file will be deleted from your system.
Listing 5.9
using System;
using System.IO;
class CreateFile
{
public static void Main()
{
FileInfo finfo = new FileInfo(@"D:\Mycsharp.txt");
FileStream fstream = finfo.Create();
Console.WriteLine("File Mycsharp.txt created");
Console.WriteLine("Creation Time: {0}",finfo.CreationTime);
Console.WriteLine("Full Name: {0}",finfo.FullName);
Console.WriteLine("FileAttributes: {0}",finfo.Attributes.ToString());
Console.WriteLine("Press any key to delete the file");
Console.Read();
fstream.Close();
finfo.Delete();
Console.WriteLine("File Mycsharp.txt deleted");
}
}
Next: Reading from a file >>
More C# Articles
More By Anand Narayanaswamy