I am writing a blog where I upload text documents to a directory that contain HTML. Using the code below, do you anticipate I will have any issues with file locking or other problems I am not seeing? I am most concerned about the File.ReadAllText().
The directory will contain a list of files ex:
20120101_2300.txt
20120201_0100.txt
etc…
public class Website
{
private string directory = "C:\\Web";
public List<BlogEntry> GetArchives()
{
return GetArchives("");
}
public List<BlogEntry> GetArchives(string date)
{
var files = !string.IsNullOrEmpty(date) ? Directory.GetFiles(directory, "*.txt").Where(t => t.Contains(date)) : Directory.GetFiles("C:\\Web", "*.txt");
var sb = files.Select(file => new BlogEntry {FullPath = file}).ToList();
return sb.OrderByDescending(t => t.FileDate).Skip(5).ToList();
}
public List<BlogEntry> GetRecent()
{
var files = Directory.GetFiles(directory, "*.txt");
var sb = files.Select(file => new BlogEntry {FullPath = file}).ToList();
return sb.OrderByDescending(t => t.FileDate).Take(5).ToList();
}
}
public class BlogEntry
{
public string FullPath { get; set; }
public DateTime FileDate
{
get { return DateTime.ParseExact(Path.GetFileNameWithoutExtension(FullPath), "yyyyMMdd_HHmm", CultureInfo.InvariantCulture); }
}
public string FileContents
{
get { return File.ReadAllText(FullPath); }
}
}
As long as you’re sure there’s only one writer to a file (ie: yourself), this can work. More than that, and you’re likely to get into trouble. If you’re okay with this restriction, though, all you need to do is make sure to use a
FileStreamwith the appropriateFileShareenumeration. It’s pretty easy if you wrap it in aStreamReader.Write the property like this:
For performance, if your server has the ram, you’ll like do much better if you load these into a dictionary in memory the first time each record is asked for. Your code would look in the dictionary first and only read the file if the dictionary doesn’t have it.