Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

UnauthorizedAccessException

Status
Not open for further replies.

zackiv31

Programmer
May 25, 2006
148
0
0
US
Here's my code:
Code:
string drive = "c";
TextReader tr = new StreamReader(String.Format(@"{0}:\boot.ini.zives",drive));
tr.WriteLine("test");
tr.Flush();
tr.Close();

I'm running it under Administrator mode (the account), but I'm getting an access denied, with an UnauthorizedAccessException. The file isn't read only, although It's a system file. Any ideas on how to write to the boot.ini file?
 
On which line did you say you're getting an exception?

Btw, you can't use a stream reader for write operations, hence a reader. use a stream writer.

[wink]
 
Normally the above code will not compile since the TextReader class has no WriteLine method.

You should change your code like this by using StreamWriter and TextWriter:

string drive = "c";
TextWriter tw = new StreamWriter(String.Format(@"{0}:\boot.ini.zives", drive));
tw.WriteLine("test");
tw.Flush();
tw.Close();

Greetz,

Geert

Geert Verhoeven
Consultant @ Ausy Belgium

My Personal Blog
 
Oops, sorry that's just a typo, I've been coding all day...

I did use textWriter and Streamwriter, but it throws an error on the instantiation.

Any ideas now?
 
Here's a better written version of my problem, the first one is totally wrong:

Code:
string drive = "c";
TextWriter tw = new StreamWriter(String.Format(@"{0}:\BOOT.INI",drive));
tw.WriteLine("test");
tw.Flush();
tw.Close();

It has to do with the fact that I'm writing the BOOT.INI file of windows, since it's a system file I guess? But I'm running the program with administrator privileges, so it should work.
 
Afaik, you cannot write on a file with S, H, or R attributes (System, Hidden, Read-only) and Boot.INI has all 3 set.

To edit it, you must remove first these 3 attributes using System.IO.FileInfo.Attributes, do your changes on the file, then put back the attributes again.
Code:
System.IO.FileInfo fi = new System.IO.FileInfo("c:\\boot.ini");
			// Remove Hidden attribute
			fi.Attributes ^= System.IO.FileAttributes.Hidden;
			// Set Hidden attribute
			fi.Attributes |= System.IO.FileAttributes.Hidden;
 
I solved this at about the same time as you.

I Get it's attributes first, store them temporarily, set the files attributes to Archive, do all my writing, and reset the original attributes.

My boot.ini wasn't read only, so I think it was the system or hidden value that made it impossible to write... do you know which one?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top