When calling File.WriteAllText to generate files, intermittently the c# windows form program will hit a catch block due to an Exception with the message of "FileStream was asked to open a device that was not a file. For support for devices like 'com1:' or 'lpt1:', call CreateFile, then use the FileStream constructors that take an OS handle as an IntPtr."
The stacktrace shows Microsoft.Win32.Win32Native.SafeCreateFile as being where it got to last.
After days of researching and trying to find out why this was happening, most articles talk about the reserved file names like com and etc. However, this exception is hit in the middle of exporting files after getting through a few files already. These files don't have any reserved names in them. They all have the same path except for at the end of the file name where a hyphen and padded number for which file it is on is added. Since this gets through similar named files, I believed that this wasn't what was actually happening. The other issue is I could do the same export process multiple times and not get it to happen every time. In fact out of 100 or so export processes it would maybe happen only once even though nothing in the name or path had changed.
Today I found a way to actually get it to happen almost every time. If I go to Chrome and open say "a.singlediv.com" to test with, start the export, then as the export is running I repeatedly reload the div site, it will 99% of the time halt the export and hit the exception mentioned above.
Does anyone have any advice that could lead me to why this Exception message is shown for doing this? Task Manager doesn't seem to have any glaring issues with Memory or CPU overload and a log is being posted to our SQL server after hitting the Exception so I also dont believe it is a network issue.
Update
I was able to find out more about when the error happens with testing yesterday. When refreshing the website repeatedly, I tried a couple different ways of exporting to get more information.
A custom configuration file, a text file, and an excel file are used as setup files for our program. I made identical folders on the Desktop and on a mapped drive which points to a folder located on our server for where the setup files are located as well as where the exports will be saved. I tried a couple different ways of loading these files and export locations.
If I load the setup files from the Desktop folder and save to the Desktop, or load from the Desktop folder and save to the mapped drive, or load from the mapped drive and save to the Desktop folder all of these don't seem to hit the Exception. So far the only way I have gotten the Exception to occur is when I load from the mapped drive and save to the mapped drive while doing the constant refreshing of the div website.
Attached below is a screenshot of the Exception.ToString() (Except for our custom methods that called File.WriteAllText() before in the StackTrace). I manually added returns between each method call so that it is easier to read.
Workaround Update
Per Mason's suggestion I wrapped my File.WriteAllText call in a Polly Retry which has seemed to so far allowed the export to finish every file while debugging the code.
I first did a RetryPolicy.Execute that wrapped the File.WriteAllText. Before File.WriteAllText I wrote the Attempt # it was on to the Output window and after it wrote a message about completing. I did get an Attempt #2 but was getting Attempt #1 and completed for every time it was called which was not easy to see since it happens over 2000 times. So I tried to add an if statement to check if this was not the first attempt and if it wasn't it would write the Attempt # and that the retry handled Exception to the Output window. However, after adding these if statements I didn't get any Attempt #s and it didn't break on the Exception but I also saw that the Output window did have a line about hitting the Exception so I assume that means that the Retry handled it? I would of expected to see Attempt #2 and Retry handled Exception around the Exception message in the Output window since it didn't stop and created every file needed. I have added a code snippet of what I added below.
int attempt = 0;
Polly.Retry.RetryPolicy retryIfException = Policy.Handle<System.NotSupportedException>().Retry(3);
retryIfException.Execute(() =>
{
if (attempt>0)
{
Console.WriteLine($"Attempt #{++attempt}");
}
File.WriteAllText(saveLocation, this.currentFileText.ToString());
if (attempt>1)
{
Console.WriteLine("Retry handled Exception");
}
});
I've been working on this for the past month and am trying to get the final connection.
so far, I can open Revit, execute an Autocad DLL from a Revit button however I don't know how to pull the information back into the Revit API. I have tried a couple of different methods however I've come to a wall. Here are the options I've tried with explanations below
1) Combine the DLL file and the Revit Button API file into one using classes.
---> Trying this method leaves me with an error when loading an existing CAD file. I don't get this error if I'm creating a new CAD file or if I'm running the DLL by itself with Autocad set to Debug.
Grabbing CAD file failed.
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
e.StackTrace:
at AcDbDatabase.{ctor}(AcDbDatabase* , Boolean , Boolean )
at Autodesk.AutoCAD.DatabaseServices.Database..ctor(Boolean buildDefaultDrawing, Boolean noDocument)
at CAD2Revit.AutoCadOperations.grabCAD(String filepath)
at CAD2Revit.Command.Execute(ExternalCommandData commandData, String& message, ElementSet elements)
when trying to run this line:
// Create a database and try to load the file
Autodesk.AutoCAD.DatabaseServices.Database db = new Database(false, true); // error occuring here often
I've done some research on the error and this is the only close repoo
2) Keep them separate
--> In this option, I've figured out how programatticly open AutoCAD, netload a DLL, and then execute it which grabs the file information but then I cant return the info to the Revit API
Any wisdom or advice is appreciated on how to approach this.
this is the closest post i've seen similar to this but its in VB i think and is over my head.
https://forums.autodesk.com/t5/net/system-accessviolationexception-attempted-to-read-or-write/td-p/4796397
I see no reason why such a problem should appear. If all else fails, you could always use IPC to separate the two processes. However, there should not really be any need for this.
I work on an app where user can type in some text. Text is saved to XML file, I try to make the file save “on the fly” as user is typing so it saves instantly. However if data is typed quick, I get an error of “file currently in use”. How to overcome this issue?
The reason for the error is that you are trying to write a file while the previous write operation is incomplete and the file is still open for write.
Now, if you absolutely must make a write on every character change - I would put in a queue in place, so when XML content is changed - instead of writing to a file right away - agg a message to a queue. Then have the code that monitors that queue and only writes the next chnage once the previous write has finished.
You can try to put a flag to control if the file is already open or not. If this is open, you keep the text and don't write on XML, but if it is not you just write.
This is a concurrency problem, you can acess the website: https://www.oreilly.com/library/view/concurrency-in-c/9781491906675/ch01.html to get more options.
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";
First and foremost, thank you to anyone who is able to help with this seemingly simple problem I am having. Background: I have an application that uploads files to a server using Rebex. What I need to do for testing purposes is create a fake file, place it in the middle of all other files, and then create an exception in the program that catches that fake file (we'll call it "fileX"), and throws an error. Basically, the point of the test is to see what happens when the upload has to stop mid-upload process.
My upload code is as follows:
Server.Upload(source, "/", Rebex.IO.TraversalMode.Recursive, Rebex.IO.TransferMethod.Copy, Rebex.IO.ActionOnExistingFiles.OverwriteOlder);
Server.Disconnect();
What do I need to add under this code in order to stop the upload once it reaches "fileX"? I cant find any documentation on this type of test specifically.
Thank you!