I have a program that will check if .csv file is created. If created, do something, if not wait untill its created. Is it possible in C#?
Tried something like this but didn't work well...
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(1);
var timer = new System.Threading.Timer((e) =>
{
if (!File.Exists(@"TestFileLocation"))
{
MethodName(); //Tried this to start method agian
}
else
{
HereIsRestOfTheCodeToDoSomeActions();
}
}, null, startTimeSpan, periodTimeSpan);
If my post isn't clear enough, sorry I'm not fluent in English, below are steps, how program will work:
- Check if file is created in folder
- If not, wait 1 minute and check again
- If file is created do some things
- Loop this steps from start
CodePudding user response:
The perfect fit for your problem would be to use a FileSystemWatcher. Its job is to watch a directory for changes such as the creation of files as you need it in your problem.
That would also make the one-minute-threshold obsolete. Consider for example:
// necessary assembly using for using FileSystemWatcher classes.
using System.IO;
// ...
// instantiate your watcher.
using var watcher = new FileSystemWatcher(@"C:\path\to\folder");
// just filter for interesting attribtes.
watcher.NotifyFilter = NotifyFilters.FileName;
// attach an event handler to the event that is triggered when a file is created.
watcher.Created = OnCreated;
// ...
// implement the event handler.
private static void OnCreated(object sender, FileSystemEventArgs e)
{
// if the name is "your" name, you're ready to go ...
if (e.Name == "my_name")
// do something ...
}
However, if you still want to use a loop (due to constraints you didn't state in your post), then it might probably be something like the following less adorable approach:
var now = DateTime.Now;
var waitTime = TimeSpan.FromMinutes(1);
while (true)
{
if (!File.Exists(@"TestFileLocation"))
{
// do something ...
// exit the loop.
break;
}
Thread.Sleep(waitTime);
}
Note and take care that this endless-loop blocks the main thread until you found your file. A better approach would be to execute that task in a separate thread aside from the main thread.
CodePudding user response:
Create FileSystemWatcher https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=net-6.0 and add check in OnCreated