PEPTool/AV-ToolV3/Writer.cs
2019-11-21 08:32:45 +01:00

94 lines
3.6 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PEP_Tool
{
public static class Writer
{
static int errCount = 0;
static bool ready = true;
public static async Task<FileStream> WaitForFile(string fullPath, FileMode mode, FileAccess access, FileShare share)
{
ready = false;
var err = false;
FileStream fs = null;
var r = new Random();
for (int numTries = 0; numTries < 50; numTries++)
{
fs = null;
try
{
await Task.Delay(r.Next(5, 100));
if (err && errCount > 20)
{
LogFile.WriteLine(access.ToString() + "error #" + errCount + ": " + Path.GetFileName(fullPath));
await Task.Delay(r.Next(200, 1000));
}
fs = new FileStream(fullPath, mode, access, share);
if (err && errCount > 20) LogFile.WriteLine(access.ToString() + " done" + ": " + Path.GetFileName(fullPath));
err = false;
errCount = 0;
ready = true;
return fs;
}
catch (IOException ex)
{
await Task.Delay(r.Next(5, 100));
errCount++;
System.Diagnostics.Debug.WriteLine("Writer_IOException: " + DateTime.Now.TimeOfDay);
//LogFile.WriteLine($"{Environment.MachineName}: {access.ToString()} denied: {Path.GetFileName(fullPath)}\n\nDies ist das {errCount}. vorkommen\n\n");
//LogFile.WriteLine(ex.ToString());
//LogFile.WriteLine("Message: " + ex.Message);
//if(ex.InnerException != null) LogFile.WriteLine("InnerException: " + ex.InnerException);
err = true;
if (fs != null)
{
fs.Dispose();
}
await Task.Delay(r.Next(200, 500));
ready = true;
}
catch (Exception exc)
{
//LogFile.WriteLine(Environment.MachineName + ": " + access.ToString() + " denied" + ": " + Path.GetFileName(fullPath));
//LogFile.WriteLine(exc.ToString());
//LogFile.WriteLine("Message: " + exc.Message);
//if (exc.InnerException != null) LogFile.WriteLine("InnerException: " + exc.InnerException);
err = true;
if (fs != null)
{
fs.Dispose();
}
await Task.Delay(r.Next(200, 500));
ready = true;
}
}
//fs.Dispose();
if (err) System.Windows.MessageBox.Show("Daten konnten nicht geschrieben werden!\nBitte erneut versuchen\n\nWenn dieser Fehler mehrmals direkt hintereinander auftritt, bitte an Marcus Bachler wenden.", "Fehler", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning, System.Windows.MessageBoxResult.OK);
ready = true;
return null;
}
}
}