Как я ожидаю Файла, чтобы быть Свободным так, чтобы ss.Save()
может перезаписать его с новым. Если я выполняю это дважды близко друг к другу (выход), я получаю a generic GDI+
ошибка.
///<summary>
/// Grabs a screen shot of the App and saves it to the C drive in jpg
///</summary>
private static String GetDesktopImage(DevExpress.XtraEditors.XtraForm whichForm)
{
Rectangle bounds = whichForm.Bounds;
// This solves my problem but creates a clutter issue
//var timeStamp = DateTime.Now.ToString("ddd-MMM-dd-yyyy-hh-mm-ss");
//var fileName = "C:\\HelpMe" + timeStamp + ".jpg";
var fileName = "C:\\HelpMe.jpg";
File.Create(fileName);
using (Bitmap ss = new Bitmap(bounds.Width, bounds.Height))
using (Graphics g = Graphics.FromImage(ss))
{
g.CopyFromScreen(whichForm.Location, Point.Empty, bounds.Size);
ss.Save(fileName, ImageFormat.Jpeg);
}
return fileName;
}
Такая функция сделает это:
public static bool IsFileReady(string filename)
{
// If the file can be opened for exclusive access it means that the file
// is no longer locked by another process.
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
return inputStream.Length > 0;
}
catch (Exception)
{
return false;
}
}
Вставьте ее в цикл while
, и у вас будет что-то, что будет блокироваться, пока файл не станет доступным:
public static void WaitForFile(string filename)
{
//This will lock the execution until the file is ready
//TODO: Add some logic to make it async and cancelable
while (!IsFileReady(filename)) { }
}
Нет функции, которая позволила бы вам ждать, когда конкретный дескриптор / расположение файловой системы станет доступным для записи. К сожалению, все, что вы можете сделать, это запросить ручку на предмет записи.
bool isLocked = true;
while (isLocked)
try {
System.IO.File.Move(filename, filename2);
isLocked = false;
}
catch { }
System.IO.File.Move(filename2, filename);