Tutorial by Examples

To delete a file (if you have required permissions) is as simple as: File.Delete(path); However many things may go wrong: You do not have required permissions (UnauthorizedAccessException is thrown). File may be in use by someone else (IOException is thrown). File cannot be deleted because ...
To change a text file is not easy because its content must be moved around. For small files easiest method is to read its content in memory and then write back modified text. In this example we read all lines from a file and drop all blank lines then we write back to original path: File.WriteAllLi...
Text is saved encoded (see also Strings topic) then sometimes you may need to change its encoding, this example assumes (for simplicity) that file is not too big and it can be entirely read in memory: public static void ConvertEncoding(string path, Encoding from, Encoding to) { File.WriteAllT...
This example updates last write time of a huge number of files (using System.IO.Directory.EnumerateFiles instead of System.IO.Directory.GetFiles()). Optionally you can specify a search pattern (default is "*.*" and eventually search through a directory tree (not only the specified director...
This snippet is an helper function to enumerate all files older than a specified age, it's useful - for example - when you have to delete old log files or old cached data. static IEnumerable<string> EnumerateAllFilesOlderThan( TimeSpan maximumAge, ...
File.Move In order to move a file from one location to another, one simple line of code can achieve this: File.Move(@"C:\TemporaryFile.txt", @"C:\TemporaryFiles\TemporaryFile.txt"); However, there are many things that could go wrong with this simple operation. For instance, wh...

Page 1 of 1