我有一個Web服務,檢查字典,看看是否存在一個文件,然後如果它存在它讀取文件,否則它保存到文件。這是來自一個網絡應用程序。我不知道最好的辦法是什麼,因爲如果同時訪問同一個文件,我偶爾會得到FileNotFoundException異常。 下面的代碼的相關部分:文件流寫入文件和讀取文件
String signature;
signature = "FILE," + value1 + "," + value2 + "," + value3 + "," + value4; // this is going to be the filename
string result;
MultipleRecordset mrSummary = new MultipleRecordset(); // MultipleRecordset is an object that retrieves data from a sql server database
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);
}
下面的代碼,看看是否該文件已經存在:
private static Dictionary<String, bool> dict = new Dictionary<String, bool>();
public bool existsFile(string signature)
{
if (dict.ContainsKey(signature))
{
return true;
}
else
{
return false;
}
}
這是我用來檢索如果它已經存在:
try
{
byte[] buffer;
FileStream fileStream = new FileStream(@System.Configuration.ConfigurationManager.AppSettings["CACHEPATH"] + filename, FileMode.Open, FileAccess.Read, FileShare.Read);
try
{
int length = 0x8000; // get file length
buffer = new byte[length]; // create buffer
int count; // actual number of bytes read
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() + "\"}";
}
如果該文件以前不存在,則會將JSON保存到文件中:
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 {
}
這裏有詳細的例外,我有時運行上面的代碼獲得:
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)
相當高的WTF/LOC比之前,我必須說... – SWeko 2010-06-08 17:42:05