OpenWrite UnauthorizedAccessException - c#

I am working on a desktop application that internally creates a StringBuilder that errors get appended to and ultimately gets written to a txt file.
I get an exception that says 'Access to the path 'C:\Users\Me\Documents\test_dir\5_hundred_thousand_rows_Logs.txt' is denied.'
Below is the code that performs the creation of the .txt file. The exception catches on the File.OpenWrite(tempfile)) line
string tempfile="C:\\Users\\Me\\Documents\\test_dir\\5_hundred_thousand_rows_Logs.txt";
using (Stream fileStream = File.OpenWrite(tempfile))//exception here
{
string data = logFileContent.ToString();
Byte[] filecontent = new UTF8Encoding(true).GetBytes(data);
fileStream.Write(filecontent, 0, filecontent.Length);
}
Process.Start(tempfile);
I have double checked and the tempfile does indeed have the file extension and is not attempting to create a directory.
I've tried wrapping the using statement with the following to attempt to "grant" access but to no avail:
var permissionSet = new PermissionSet(PermissionState.None);
var writePermission = new FileIOPermission(FileIOPermissionAccess.AllAccess, Path.GetDirectoryName(tempfile));
writePermission.Demand();
permissionSet.AddPermission(writePermission);
FileAttributes attributes = File.GetAttributes(Path.GetDirectoryName(tempfile));
if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
{
// using statement
}
I am wanting this desktop application to be able to be handed to anyone and they be able to use this without having the user deal with folder permissions or something. Granted I'm really only expecting it to try to access MyDownloads, MyDocuments, directories on flash drives or other similar devices.
I would greatly appreciate any help provided.
EDIT:
It appears that this may be a Windows issue. The file is set to readonly in its properties (was not this way originally), and attempting to set the file as not readonly doesn't work as Windows apparently just resets it back to readonly. However if the file is not in a folder and is just sitting on the bare drive (such as a different drive eg: D:/5_hundred_thousand_rows_Logs.txt) it seems to work just fine. If there's a programmatic way to get around this I would appreciate it, but if this is a Windows issue this may require making this a different question.

According to the documentation the exception is thrown when you don't have the permissions, or the file is readonly.
To test if you don't have permissions, try and run your application as administrator. To verify the second case, right click the file in explorer, choose properties, and make sure it's not readonly.
Besides that string tempfile="C:\\Users\\Me\\Documents\\test_dir\\5_hundred_thousand_rows_Logs.txt"; is a weird path, because it's using the user me which definitelly doesn't exist on every machine. If you like to get the documents folder of the current user you can use: Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); This will create the correct path for you.

Related

Why am I getting a "Could not find a part of the path" exception?

I am developing website using Visual Studio 2010. I am trying to save a file in a path. It works fine localhost.
But the same code is not working in IIS. It shows the following error
Exception Details: System.IO.DirectoryNotFoundException: Could not
find a part of the path 'C:\Inetpub\wwwroot\Vendor\cn.jpg'.
Could not find a part of the path 'C:\Users\shashank\Desktop\ab.csv'.
Here is the code:
protected void btnImportFile_Click(object sender, EventArgs e)
{
sArReportText = File.ReadAllText(txtFilePath.Text.Trim());
// Set the report Properties to insert Report information
SetProperties();
}
You might also be experiencing what I am: that the directory name contains some unusual characters. In my case,
Could not find a part of the path 'C:\Web\metBoot\wild iis\DigiCert© Certificate Utility for Windows_files'.
That copyright sign is the issue.
So using concepts drawn from Obtaining the short 8.3 filename from a long filename, I convert my paths to short form first, then use that to get my list of files.
StringBuilder sf = new StringBuilder(300);
int n = GetShortPathName(sourceFolder, sf, 300);
if (0 == n)
{
tk.write(Marshal.GetLastWin32Error().ToString());
continue;
}
...
IEnumerable<string> fileGroup = Directory.EnumerateFiles(sf.ToString(), ext);
Consider how you're launching VS too. Counter-intuitively I run into this problem only when I'm running VS in Administrator mode. Possibly a group policies thing.
This may be because, you are not having the specified file in web server, or you may be used an incorrect path. Specify the exact folder and filename as how it is stored in the web server. use HttpContext.Current.Request.ApplicationPath or Server.MapPath to specify the correct location where your desired file lies. And also make sure that you have given read and write permissions for this specific file and its folder.
You need to have permissions set in iis to allow files to be saved in the folder. Basically your uploaded files should be saved inside a separate folder present inside your root directory.
In order to access, create and delete files on the server, must have rights.
Like in my project I am using Impersonator class to access various files and folder from the server.
Otherwise it will throw an exception.
You could use code impersonation:
http://csharptuning.blogspot.com/2007/06/impersonation-in-c.html
http://www.codeproject.com/Articles/14358/User-Impersonation-in-NET
regardless, whomever you use as the impersonation must be able to read/write to the location that is being saved to. We use this method in applications for delete/create folders across network. Even if App_Data is best practice, it may be a business requirement to access the documents outside of that folder.
You can also set impersonation on IIS.
I also notice that your function is called btnImportFile. You may want to look into FileUpload control if you are uploading a file, which allows you to get the byte array of the file and save as needed. https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload%28v=vs.110%29.aspx. You might still need to use Server.MapPath or HttpContext.Current.Request.ApplicationPath depending on your needs.
It's usually best practice to use the App_Data folder to save files to.
Take a look here, Working with files, for a tutorial.

StreamWriter creating Directory instead of File

Really confused here. I'm running Windows 7 and on an Administrator account, but for some reason, the following code is falling down;
public static readonly string Report = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "report.csv");
StreamWriter sw = new StreamWriter(Report, true);
I get the following error;
Access to the path 'C:\Users\Trent\Desktop\report.csv' is denied.
Then, when I look on the Desktop I have a Folder called "report.csv" instead of a file...
I know it's probably something really basic, but I have no idea what it is, anybody have any ideas?
Somewhere else in your code you are creating that directory. Either that, or it's been there all along.
Dig through the rest of your code looking for where you use the Report field.
The code you have posted is fine.

Access to the path denied error in C#

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";

How to read text from a text file in the XAP?

I'm working on an out-of-browser Silverlight program, and I have successfully gotten it to open local files by means of an OpenFileDialog. However, now I need it to open a file from within its own XAP (no browsing necessary, the file to open is hard-coded). I am trying to use this code, but it's not working:
using (StreamReader reader = new StreamReader("Default.txt"))
{
TextBox1.Text = reader.ReadToEnd();
}
This code throws a SecurityException that says "File operation not permitted. Access to path 'Default.txt' is denied." What am I doing wrong?
Your code is trying to open a file called "Default.txt" that is somewhere out in the user's file system. Where exactly I don't know, as it depends on where the Silverlight app's executing from. So yes, in general you don't have permission to go there.
To pull something out of your XAP, you need ton construct the stream differently. It will be along these lines:
Stream s = Application.GetResourceStream(
new Uri("/MyXap;component/Path/To/Default.txt", UriKind.Relative)).Stream;
StreamReader reader = new StreamReader(s);
Note, this means your Default.txt should be set to 'Resource', not 'Embedded Resource'. By being a 'Resource' it will get added to the XAP. Embedded Resource will add it to the assembly.
More info: http://nerddawg.blogspot.com/2008/03/silverlight-2-demystifying-uri.html
Note: In cases where your Silverlight program has multiple assemblies, check that the "/MyXap" part of the Uri string references the name of assembly containing the resource. For example if you have two assemblies "ProjectName" and "ProjectName.Screens", where "ProjectName.Screens" contains your resource, then use the following:
new Uri("ProjectName.Screens;component/Path/To/Default.txt", UriKind.Relative))

System.UnauthorizedAccess Exception C#

I currently have a compiled C# program but whenever I run it I get the Windows encountered a problem error.
This is from a System.UnauthorizedAccess error, how can I give access and remove this error without any need from the user side, since this program is being deployed to a lot of people and I don't want them having to make this fix manually.
Thanks
You can get the current user's application data folder using the environment variable APPDATA. Therefore, you can do something like:
string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
string configFile = Path.Combine(appdata, configFile);
StreamWriter writer = new StreamWriter(configFile);
writer.WriteLine("my config data");
writer.Close();
You can also use this approach to get the temporary folder as well. You can even generate a random file name using the BCL functions. I think it's Path.GetTempFilename().
Does your application ask for Administrator's privileges at any time?

Categories