C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
6,968 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Tests
{
class Program
{
static long oldFileSize;
static bool firstTimeSaveGame = false;
static string rootSaveGameDirectory;
static void Main(string[] args)
{
FileSystemWatcher fileWatcher = new FileSystemWatcher(@"C:\Program Files (x86)\saves");
// Enable events
fileWatcher.EnableRaisingEvents = true;
rootSaveGameDirectory = @"C:\Program Files (x86)\saves";
if (!Directory.Exists(rootSaveGameDirectory))
{
Directory.CreateDirectory(rootSaveGameDirectory);
}
string fileToWatch = @"C:\Program Files (x86)\MySave";
while (!File.Exists(fileToWatch))
{
if (File.Exists(fileToWatch))
{
FileInfo fi = new FileInfo(fileToWatch);
oldFileSize = fi.Length;
firstTimeSaveGame = true;
CopyFileOnChanged(fileToWatch, fileToWatch);
Console.WriteLine("File copied first time...");
break;
}
}
fileWatcher.Path = Path.GetDirectoryName(fileToWatch);
fileWatcher.Filter = Path.GetFileName(fileToWatch);
// Add event watcher
fileWatcher.Changed += FileWatcher_Changed;
fileWatcher.Created += FileWatcher_Changed;
fileWatcher.Deleted += FileWatcher_Changed;
fileWatcher.Renamed += FileWatcher_Changed;
var maxThreads = 4;
// Times to as most machines have double the logic processers as cores
ThreadPool.SetMaxThreads(maxThreads, maxThreads * 2);
Console.WriteLine("Listening");
Console.ReadLine();
}
}
}
Even if if the file exist when i create it it's never get inside and reaching the lines :
FileInfo fi = new FileInfo(fileToWatch);
oldFileSize = fi.Length;
firstTimeSaveGame = true;
CopyFileOnChanged(fileToWatch, fileToWatch);
Console.WriteLine("File copied first time...");
It's jumping right to the line :
Console.WriteLine("Listening");
How the conditions in the while loop should be like ?
Maybe put delay in there to allow the file to create before the if statement. If you use Task.Delay it wont lock up the app while waiting
while (!File.Exists(fileToWatch))
{
var t = Task.Run(async
{
await Task.Delay(1000);
});
t.Wait();
if (File.Exists(fileToWatch))
{
FileInfo fi = new FileInfo(fileToWatch);
oldFileSize = fi.Length;
firstTimeSaveGame = true;
CopyFileOnChanged(fileToWatch, fileToWatch);
Console.WriteLine("File copied first time...");
break;
}
}
This code makes no sense
while (!File.Exists(fileToWatch))
{
if (File.Exists(fileToWatch))
{
….
}
}
The while loop only executes the if statement if no file exists. If a file exists it does enter the loop and execute the if. So the if is only executed when it is false.