FolderWatcher.Created fires, but file doesn't exist- NAS - c#

I'm facing a very weird problem.
I have a C# project with a FolderWatcher.OnCreate on a specific LAN path.
FolderWatcher.Created += new FileSystemEventHandler(FSW_Created);
I'm working simultaneously with two systems on the NAS so when one system finishes to work - it "tells" the other by copying a file (File.Copy) to some location.
The second system is listening to that location (don't ask why that's the way of implementing that...it's a long story)
When the copy of the original file is created - the second system searches for the original copy.
This works for all these file, except of sometimes when I get a message that the original's directory doesn't exist...
I see the directory is correct, and it happens only for a few such files. It has to exist (and it actually exists) because the copy came from there....
If anyone has a clue - I'll be glad.
when the error happens I enter into the following code line:
if (!Directory.Exists(directoryPath))
Currently I just added a path - try 50 times, every second, until you find it... I can't check it now, but I guess it will work
Thanks

Related

Split PDF and save but Access is denied [duplicate]

I have read a similar post, but i just cant figure out the problem.
I have changed the windows permissions and changed routes.
When i try to save a file it throws me the exception:
Access to the path **** denied.
string route="D:\\";
FileStream fs = new FileStream(route, FileMode.Create); <--here is the problem
StreamWriter write = new StreamWriter(fs);
patient person = new patient();
patient.name = textBox1.Text;
patient.name2 = textBox2.Text;
You are trying to create a FileStream object for a directory (folder). Specify a file name (e.g. #"D:\test.txt") and the error will go away.
By the way, I would suggest that you use the StreamWriter constructor that takes an Encoding as its second parameter, because otherwise you might be in for an unpleasant surprise when trying to read the saved file later (using StreamReader).
Did you try specifing some file name?
eg:
string route="D:\\somefilename.txt";
tl;dr version: Make sure you are not trying to open a file marked in the file system as Read-Only in Read/Write mode.
I have come across this error in my travels trying to read in an XML file.
I have found that in some circumstances (detailed below) this error would be generated for a file even though the path and file name are correct.
File details:
The path and file name are valid, the file exists
Both the service account and the logged in user have Full Control permissions to the file and the full path
The file is marked as Read-Only
It is running on Windows Server 2008 R2
The path to the file was using local drive letters, not UNC path
When trying to read the file programmatically, the following behavior was observed while running the exact same code:
When running as the logged in user, the file is read with no error
When running as the service account, trying to read the file generates the Access Is Denied error with no details
In order to fix this, I had to change the method call from the default (Opening as RW) to opening the file as RO. Once I made that one change, it stopped throwing an error.
I had this issue for longer than I would like to admit.
I simply just needed to run VS as an administrator, rookie mistake on my part...
Hope this helps someone <3
If your problem persist with all those answers, try to change the file attribute to:
File.SetAttributes(yourfile, FileAttributes.Normal);
You do not have permissions to access the file.
Please be sure whether you can access the file in that drive.
string route= #"E:\Sample.text";
FileStream fs = new FileStream(route, FileMode.Create);
You have to provide the file name to create.
Please try this, now you can create.
TLDR : On my end, it had something to do with AVAST ! => Whitelist your application.
All of a sudden, I also got this UnauthorizedAccessException problem in the windows WPF program I'm writing. None of the solutions worked - except I couldn't figure out how to elevate my application to full privileges (not using VS) while at the same time, being already on the administrator account, I didn't feel the need to dig that deep in permission concerns.
The files are image files (jpg, psd, webp, etc.) I wasn't trying to open/write a directory, it has always been a valid path to a file, and I needed to write to the file, FileAccess.ReadWrite was inevitable. The files (and any of their parent directory) were not readonly (I even checked by code prior calling new FileStream(path, mode, access, share) via FileInfo.IsReadOnly) - so what happenned all of a sudden ???
Thinking about : I had an had drive crash, so I unpacked a backup of my solution code from another drive. In the meantime, I added codes in my application to PInvoke APIs to directly read hard drive sectors physical bytes as well as USB plug/unplug monitoring.
I started to get the Exception when I added those, but even though I temporarly removed the related codes from the application, I still got the UnauthorizedAccessException.
Then I remembered one thing I've done long ago, a painstaking similar issue where I wanted my application to communicate sensible data via Wifi, which was to add the executable among AVAST exceptions, and the assembly directory aswell (My app was already among the authorized apps through firewall)
Just did it for my application in AVAST settings, AND THE EXCEPTION IS GONE !!! Two whole days I'm lurking StackOverflow and the web to get moving on, FINALLY !
Details : I can't pinpoint exactly what AVAST didn't like in my application as the only changes I made :
Retrieved then launched the backup code - it worked like a charm, files (images) opens/write without problems (3 days ago)
Added USB detection (3 days ago - Just tested the code, didn't tried to open an image)
Added PInvoke physical drive direct read (2 days ago - FileStream, and the logic to define where/how to scan the damaged drive - Just tested the code, didn't tried to open an image)
Added image format detection starting from Jpg/Jfif.. 2 days ago, got the exception upon testing the code.
While searching for solutions, added an Image Gallery WPF UserControl to diplay pictures based on their signature and check which files gives the exception : almost all of them (some files opens/write okay - why ???)
Tried everything I've found on SO (since the last 2 days) until I opened AVAST settings and whitelist my application.
... now I can move on into adding a bunch of file signatures to retrieve as many datas as I could.
If this may help those who like me, aren't failing on the "I'm passing a directory path instead that of a file", yet, have no time to learn exactly why antiviruses think our own code is a malware.
Just Using the below worked for me on OSX.
var path = "TempForTest";

Directory.Exists sensible to time?

I have the following piece of code in my application:
if (!Directory.Exists(myPath))
Directory.CreateDirectory(myPath);
If I run it in a regular unit test sometimes it passes, sometimes not. The directory is always there (I made sure of it, so technically it will never be "created" by code). But every once in a while Directory.Exists(myPath) returned false, which makes the code try to create the folder and then I get an UnauthorizedAccessException!
The funny thing here is if I put a breakpoint on the CreateDirectory, and then move the yellow arrow up back to test, the test returns true!
What's going on?
myPath is \\nameOfLocalMachine\sharedFolder. The share is reliable and constantly used... .NET 4.0
I just made a fiddler simulate 3000 sequentials requests. 175 failed... All with the same message:
Access to the path '\nameOfLocalMachine\sharedFolder\randomFileName.json' is denied
This mishap is pretty normal on Windows. Programs open a handle on a directory like this and specify delete sharing. Which permits anybody to delete the directory, even though the program is using it. The directory won't actually disappear from the file system until that handle is closed. What follows is that trying to recreate that directory cannot work, it still exists. Windows generates an "access denied" error, reported in your C# program with the UnauthorizedAccessException.
While that sounds like an obscure feature, every program in Windows does this. Every process has a default working directory, the value of Environment.CurrentDirectory. Creating a handle on such a directory ensures that it cannot disappear while the program is using it. There are other cases, FileSystemWatcher would be another example. Or a program busy iterating the directory. Anti-malware and search indexers are notorious for hard to diagnose sources of such errors.
Otherwise a standard hazard of a multi-tasking operating system. You are not the only one using the file system. Not repeatedly deleting and creating the same directory ought to be very high on your list. If this is absolutely necessary then rename the directory first before you delete it. You'd still fail to delete the renamed directory but you won't fail recreating it. You can delete it later, next time you need to do this. Much lower odds for trouble then. Because more time passed.

Continuously running windows service

I'm new to writing WindowsServices. I used to make web-applications.
I need to make this service that checks directories for files. If a certain trigger-file is present, the files in the directory get copied, and other stuff gets done.
My service is ready, almost.
It works fine, but I have an issue.
If the trigger-file is present, the copying and processing starts.
But at the same time, the service keeps checking my directories.
So at a given point, it comes back to the directory that is being copied.
How can I prevent it from recopying the directory?
(I hope I am clear in my explanation)
I found my solution, just when I was reading my question again and looking at your comments.
I can simply delete my trigger-file and then the service should skip the folder.
Sorry for your trouble.

My System.IO.File.WriteAllText coding doesn't create a file after it has once been deleted in Windows Explorer

CONCLUSION AT BOTTOM OF POST
I'm a novice with C# and have only just begun using System.IO, but haven't been able to find information on my issue so wanted to ask the guys here:
I have a program that when run, creates a directory, then writes to a .txt file what the most recent value of a certain variable was, so that if the program is interrupted or the computer loses power, restarting the program will retrieve that stored number from the .txt file.
I've simply done this:
string INSTATR = LastValue.ToString();
System.IO.File.WriteAllText(#"C:\\DotTempFiles\\"+Instrument.Name+"ATR.txt", INSTATR);
My first time running this program, the file was created, and I found that on every cycle the number in the file was being overwritten to the last valid number just as I wanted.
However, once I went to the DotTempFiles directory and deleted the .txt file using Shift+Del, the file has never returned upon running the program as I thought it would. If I delete the entire directory and run the program, the directory is recreated but still not the file.
If I run the program using a different Instrument.Name, that new file is created as expected, but the original one that I once manually deleted is still not showing, even after computer restarts.
I can't find any information leads online, so does anyone have an idea? Thank you!
EDIT (more info): People asked a few questions so I'm adding more information (thank you)
There are no errors being reported. It compiles fine, and when running, there is an output window that usually alerts me to errors like if I reference an object that is null, or try to read from an empty file, etc. No errors like this are occurring.
More background on what the program is. There is a stock trading program called NinjaTrader that has their own API based on C#. They wouldn't support the questions I have because it's outside the normal scope of the script development they intended people to use, and that's ok with me. The program itself is a trading strategy that is run within NinjaTrader, and it exposes default programmer access to these two main methods:
Initialize()
protected override void OnBarUpdate() //this is the main part of the program that gets called every time a change has occurred to one of the bars on the stock chart.
In the variable declaration section I have this:
System.IO.DirectoryInfo di = Directory.CreateDirectory(#"C:\\DotTempFiles");
And in OnStartUp() I have this:
//Set up ReadMe file in the temp directory in case people wonder why it keeps appearing
string README = "This DotTempFiles directory is created by the strategy every time it is run, and temporary text files with the name [instrumentsymbol]ATR.txt are written into it containing the last highest ATRStopValue for the strategy, which if it is stopped and restarted with an open position, it will read from that file to get back the best value instead of recalculating it with possibility of a lower unwanted value.";
System.IO.File.WriteAllText(#"C:\\DotTempFiles\\README.txt", README);
Every time OnBarUpdate() is called, which can be up to a few times per second, it first calculates a double called LastValue which is a number related to the stock price, then it converts it to a string INSTATR, then writes it to a .txt file.
string INSTATR = LastValue.ToString();
System.IO.File.WriteAllText(#"C:\\DotTempFiles\\"+Instrument.Name+"ATR.txt", INSTATR);
And this is every single piece of code I have connected to this issue. As I mentioned above, it created the file the first time, but since I've deleted the file in windows explorer, it isn't able to recreate it. However, deleting the directory and restarting the strategy program does recreate that directory.
OnTermination() is not being used to close or delete the file in any way (just in case people wanted to ask) -- I am not using any other code to interact with the file than the ones already shown. Thanks!
EDIT 2 (Update after reading comments): Thank you guys for your comments and help. What I'll do when I get back to my home is try recreating the minimal version of this with an empty program containing just these lines of code and see what the outcome is, and I'll post updates in either way.
EDIT 3: Thank you Steve, that is a very good idea that I should use from now on for these kinds of things.
EDIT 4 (Conclusion): Well, I found out that I overlooked something simple about my own code logic. I was setting the File.WriteAllText to trigger any time the Double variable increased in value, not on every call of the OnBarUpdate method. Because of this, the file would not be written except once every few hours or so and now I see that everything is working properly. I am sorry that I made all these people read this post since it was based on another issue of my own fault. However, I am very thankful to everyone for their comments that helped me get to this point, and to Steve and Mark Lakata for their tips that I learned some new good things from.
I found out there is nothing wrong with the file creation, it was the fact that my coding logic was just calling for it far less frequently than I assumed it was (once every few hours vs several times per second)

What folder does Path::GetTempFileName Method save to?

I need to get the temp file to see what happened because the actual file is never output. However, I can't seem to find where the temp file is created.
I need to find this out without writing code or building the application because there are too many dependencies scattered all over the place. I would not be able to deploy a debug version.
That method returns the path of a temporary file. The path will tell you where its pointing.
For example:
Console.WriteLine(Path.GetTempFileName());
produces:
C:\Users\will\AppData\Local\Temp\tmp9BD5.tmp
for me on this machine, because the TEMP environment variable is pointing to C:\Users\will\AppData\Local\Temp\
But the whole point of a method like GetTempFileName is that you shouldn't have to care where the file ends up. On the off-chance that you do, you can always get there at command prompts or file-open dialogs by using %TEMP%

Categories

Resources