I have a web service that checks a dictionary to find out if a file exists, and then if it exists, it reads the file, otherwise it saves the file. This is from a web application. Interestingly, the best way to do this is because I sometimes get a FileNotFoundException if the same file is available at the same time. Here are the relevant parts of the code:
String signature;
signature = "FILE," + value1 + "," + value2 + "," + value3 + "," + value4;
string result;
MultipleRecordset mrSummary = new MultipleRecordset();
if (mrSummary.existsFile(signature))
{
result = mrSummary.retrieveFile(signature);
}
else
{
result = mrSummary.getMultipleRecordsets(System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString(), value1, value2, value3, value4);
mrSummary.saveFile(signature, result);
}
Here is the code to find out if a file exists:
private static Dictionary<String, bool> dict = new Dictionary<String, bool>();
public bool existsFile(string signature)
{
if (dict.ContainsKey(signature))
{
return true;
}
else
{
return false;
}
}
Here is what I use to extract if it already exists:
try
{
byte[] buffer;
FileStream fileStream = new FileStream(@System.Configuration.ConfigurationManager.AppSettings["CACHEPATH"] + filename, FileMode.Open, FileAccess.Read, FileShare.Read);
try
{
int length = 0x8000;
buffer = new byte[length];
int count;
JSONstring = "";
while ((count = fileStream.Read(buffer, 0, length)) > 0)
{
JSONstring += System.Text.ASCIIEncoding.ASCII.GetString(buffer, 0, count);
}
}
finally
{
fileStream.Close();
}
}
catch (Exception e)
{
JSONstring = "{\"error\":\"" + e.ToString() + "\"}";
}
If the file did not exist before, it saves the JSON to the file:
try
{
if (dict.ContainsKey(filename) == false)
{
dict.Add(filename, true);
}
else
{
this.retrieveFile(filename, ipaddress);
}
}
catch
{
}
try
{
TextWriter tw = new StreamWriter(@System.Configuration.ConfigurationManager.AppSettings["CACHEPATH"] + filename);
tw.WriteLine(JSONstring);
tw.Close();
}
catch {
}
Here are the details of the exception that I sometimes get from executing the above code:
System.IO.FileNotFoundException: Could not find file 'E:\inetpub\wwwroot\cache\FILE,36,36.25,14.5,14.75'.
File name: 'E:\inetpub\wwwroot\cache\FILE,36,36.25,14.5,14.75'
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at com.myname.business.MultipleRecordset.retrieveFile(String filename, String ipaddress)