तीन मुद्दों, पहला यह है कि यह नकली निर्माण की घटनाओं से बाहर भेजने ताकि आप की तरह कुछ के साथ उस के लिए जाँच कर सकते हैं।
इसके बाद, आप फ़ाइल बनाने वाला इसे (इस मुद्दे को सवाल में उठाया) लेखन समाप्त करने के लिए के लिए चारों ओर इंतजार करना। और, तीसरा, आपको सावधान रहना चाहिए क्योंकि कभी-कभी फ़ाइल निर्माण ईवेंट को FileNotFoundException
दिए बिना फ़ाइल को खोला जा सकता है, लेकिन इससे पहले कि आप इसे पकड़ सकें, इसे FileNotFoundException
भी प्रदान किया जा सकता है।
private void WaitForCreatingProcessToCloseFileThenDoStuff(object threadContext)
{
// Make sure the just-found file is done being
// written by repeatedly attempting to open it
// for exclusive access.
var path = (string)threadContext;
DateTime started = DateTime.Now;
DateTime lastLengthChange = DateTime.Now;
long lastLength = 0;
var noGrowthLimit = new TimeSpan(0, 5, 0);
var notFoundLimit = new TimeSpan(0, 0, 1);
for (int tries = 0;; ++tries)
{
try
{
using (var fileStream = new FileStream(
path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
// Do Stuff
}
break;
}
catch (FileNotFoundException)
{
// Sometimes the file appears before it is there.
if (DateTime.Now - started > notFoundLimit)
{
// Should be there by now
break;
}
}
catch (IOException ex)
{
// mask in severity, customer, and code
var hr = (int)(ex.HResult & 0xA000FFFF);
if (hr != 0x80000020 && hr != 0x80000021)
{
// not a share violation or a lock violation
throw;
}
}
try
{
var fi = new FileInfo(path);
if (fi.Length > lastLength)
{
lastLength = fi.Length;
lastLengthChange = DateTime.Now;
}
}
catch (Exception ex)
{
}
// still locked
if (DateTime.Now - lastLengthChange > noGrowthLimit)
{
// 5 minutes, still locked, no growth.
break;
}
Thread.Sleep(111);
}
आप, ज़ाहिर है, अपने खुद के समय समाप्ति सेट कर सकते हैं। यह कोड 5 मिनट के लिए पर्याप्त समय छोड़ देता है। अनुरोध किए जाने पर रीड कोड में थ्रेड से बाहर निकलने के लिए ध्वज भी होगा।
मैं एक ही मुद्दा था, और इसके अलावा में FileSystemWatcher कभी कभी मैं –