text
stringlengths
0
13.4k
If file is too big to load it in memory and output path is different from input path:
File.WriteAllLines(outputPath,
File.ReadLines(inputPath).Where(x => !String.IsNullOrWhiteSpace(x)));
Section 18.3: Convert text file encoding
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.WriteAllText(path, File.ReadAllText(path, from), to);
}
GoalKicker.com – .NET Framework Notes for Professionals
73
When performing conversions do not forget that file may contain BOM (Byte Order Mark), to better understand
how it's managed refer to Encoding.UTF8.GetString doesn't take into account the Preamble/BOM.
Section 18.4: Enumerate files older than a specified amount
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,
string path,
string searchPattern = "*.*",
SearchOption options = SearchOption.TopDirectoryOnly)
{
DateTime oldestWriteTime = DateTime.Now - maximumAge;
return Directory.EnumerateFiles(path, searchPattern, options)
.Where(x => Directory.GetLastWriteTime(x) < oldestWriteTime);
}
Used like this:
var oldFiles = EnumerateAllFilesOlderThan(TimeSpan.FromDays(7), @"c:\log", "*.log");
Few things to note:
Search is performed using Directory.EnumerateFiles() instead of Directory.GetFiles(). Enumeration is
alive then you won't need to wait until all file system entries have been fetched.
We're checking for last write time but you may use creation time or last access time (for example to delete
unused cached files, note that access time may be disabled).
Granularity isn't uniform for all those properties (write time, access time, creation time), check MSDN for
details about this.
Section 18.5: Move a File from one location to another
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, what if the user
running your program does not have a Drive that is labelled 'C'? What if they did - but they decided to rename it to
'B', or 'M'?
What if the Source file (the file in which you would like to move) has been moved without your knowing - or what if
it simply doesn't exist.
This can be circumvented by first checking to see whether the source file does exist:
string source = @"C:\TemporaryFile.txt", destination = @"C:\TemporaryFiles\TemporaryFile.txt";
if(File.Exists("C:\TemporaryFile.txt"))
{
File.Move(source, destination);
}
This will ensure that at that very moment, the file does exist, and can be moved to another location. There may be
GoalKicker.com – .NET Framework Notes for Professionals
74
times where a simple call to File.Exists won't be enough. If it isn't, check again, convey to the user that the
operation failed - or handle the exception.
A FileNotFoundException is not the only exception you are likely to encounter.
See below for possible exceptions:
Exception Type