I'm learning about opening and saving files with C# and it seems that vista won't let my program save to a file on the root of C:\ , unless I run it in administrator mode.
Any ideas how to allow my program to play around with whatever files it wants?
Thanks!
private string name;
private void open_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
name = openFileDialog1.FileName;
textBox1.Clear();
textBox1.Text = File.ReadAllText(name);
textBox2.Text = name;
}
}
private void save_Click(object sender, EventArgs e)
{
File.WriteAllText(name, textBox1.Text);
}
To make your program start with administrator rights, you have to change the manifest. This can be done by Add New Item -> General -> Application Manifest File. Open the manifest and set "requestedExecutionLevel" to "requireAdministrator". When this is done, open the project settings and on the 'Application' tab choose your new manifest.
The program will run with your credentials, by default.
So, these do not have the right permissions to write to the root folder.
If you want it to run with other credentials you can us the runas command line to execute the application with other credentials.
Alternatively, grant more permissions to the account the application runs as.
There are several reasons for the UnauthorizedAccess Exception. Check one of those:
path specified a file that is read-only.
This operation is not supported on the current platform.
path specified a directory.
I accidently hit the third problem today ;-)
Related
I added a functionality to my C# windows form application which allows user to drag-drop file on the form so that the application can get the file path. I just exactly followed what's written on:
How to provide file drag-and-drop functionality in a Visual C# application
It is working on debug mode in Visual Studio environment. However, as soon as I try the same thing on individual exe file which is created on bin/Debug folder, the application does not react to drag-drop.
I have already tried to delete all the files on bin/Debug folder, but the result did not change.
It would be great if somebody has similar issue and solutions for this. Thank you.
Here are the codes I'm trying (after some try and errors it has changed a bit from what's written in the URL shown above, but this still works on Visual Studio but not on exe...) :
private void OpenFile_DragEnter(object sender, DragEventArgs e)
// enable drag-drop event
{
e.Effect = DragDropEffects.Copy;
}
private void OpenFile_DragDrop(object sender, DragEventArgs e)
// open drag-dropped setup file
{
// get drag-dropped file path
string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
// open all the files
for (int i = 0; i < s.Length; i++)
{
OpenSetup(s[i]);
}
}
Update: Another thing I found is that I can drag-drop the files on EXE from OpenFileDialog, but not from file exploler.
NOTE: The "possible duplicate" question refers to a totally and complete different theme (refering to visual studio user settings". This question is not related to that at all. Please verify before marking "possible duplicates"
I am trying to save some settings of my program between calls and I did what this tutorial says.
It works very well. A little too well...
To summarize I created settings.settings file. Then in the form closing file, I wrote code to save the settings
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.TheSetting = settingNumber;
Properties.Settings.Default.Save();
}
and in the load function code to retrieve the setting
private void Form1_Load(object sender, EventArgs e)
{
DateTime t = DateTime.Now;
if (Properties.Settings.Default.TheDate.Date == t.Date) //it is today
{
settingNumber = Properties.Settings.Default.TheSetting;
}
else
{
//we start again
settingNumber = 0;
}
textBox1.Text = settingNumber.ToString();
}
I tried and run it several times, now the setting Number is 39.
However, and this is the strange thing this value is not found anywhere. I opened the .exe.config file that is supposed to hold the setting values and they have totally different numbers. Even if I edit them (as in the tutorial) the program still runs with its number.
Where are these setting values stored?
Thanks to user swamy I found the required file.
It was in AppData folder (which is in the corresponding User Folder) then Local, and under the a folder named after the program and the file name is user.config. The path is a really long one
I read that this path can change in other versions
everyone
I have a problem with my application. I make an event that when I tick to a checkbox it will run when Window startup and I save this setting in a XML file. But it doesn't work and Window show me a message error "Stop working". Does anyone know what did I do wrong? I try to resolve it but it still. Thanks a lot. Here is my code:
private RegistryKey registrykeyApp = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\Run", true);
private void checkBoxKhoidongcungwin_CheckedChanged(object sender, EventArgs e)
{
if (this.checkBoxKhoidongcungwin.Checked)
{
if(this.registrykeyApp.GetValue("ViKey") == null)
this.registrykeyApp.SetValue("ViKey", Application.ExecutablePath.ToString(),RegistryValueKind.ExpandString);
}
else
{
this.registrykeyApp.DeleteValue("ViKey", false);
}
}
That registry key cannot be accessed from an application that is not running with elevated privileges since viruses, etc could use it to hijack computers. Unfortunately when access is denied you often get generic errors that aren't obvious.
Right click on your exe and run it as administrator and it should work. If so you can add an application manifest to your project to always request the elevated privileges automatically, without manually right clicking.
http://www.samlogic.net/articles/manifest.htm
I met a not expected problem with getting just the top directory full filenames from a specific directory. C# throws an error and doesn't list anything in the specific directory.
But MS DOS has not a problem with my command: *"dir C:\windows\prefetch\*.pf"
Visual Basics 6 old "Dir Function" also does it without complaining.
The "Windows Explorer" opens it up and doesn't ask anything from me. Also "Nirsofts Tool Suit" lists it instantly without any problem. No one of this tools needs to run with special permissions, just a double click on the application icon and ready is the task.
I looked around and found nothing here, what would answer this weird problem. My user can access the directory, if I go with any other application into it, now there is the question why C# throws
an "Unauthorized Access Exception" which is totally weird, since I have access in this folder.
I don't want to elevate my application with admin permissions for it nor create extra a xml for it to run it with highest privileges. The not trustful yellow elevation box must be avoided.
Now my question: How it comes that I can not list the filenames in this folder when all other
applications can do that.
What code do I need if "Directory.GetFiles()" fails?
Is there any flag or property in the framework directory class which allows my application access to the files, whatever.
Here my code which fails (using System.IO):
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text.Substring(0, 0); //clear the textBox1
//Unauthorized access exception and yellow bar in this line
foreach(string FileX in Directory.GetFiles(Path.Combine(Environment.GetEnvironmentVariable("windir"), "prefetch"), "*.pf"))
{
textBox1.Text += FileX;
}
}
Did I understand correctly that you only need the File-names with directory-names.
This code works for me, no elevations needed.
private void button1_Click(object sender, EventArgs e)
{
string folder = #"C:\windows\prefetch";
string filemask = #"*.pf";
string[] filelist = Directory.GetFiles(folder, (filemask));
//now use filelist[i] for any operations.
}
I am having trouble creating a .txt file with the code below. I get an exception as follows:
Unhandled exception: System.unauthorizedAccessException: Access to the
path 'C:\log.txt' is denied.
I have looked online and done similar things to what is on the api. Below is my code, so you can understand what my train of logic is. What do you think causes this exception? Thanks in advance!
static StreamWriter swt;
static string logFile = #"C:\log.txt";
static FileStream fs;
static void Main(string[] args)
{
Console.Out.WriteLine(swt);
string root = args[0];
if (!File.Exists(logFile))
{
try
{
fs = File.Create(logFile);
}
catch (Exception ex)
{
swt.WriteLine("EXCEPTION HAS BEEN THROWN:\n " + ex + "\n");
}
{
}
}
}
You're most likely getting this error because a standard user cannot write to the root of a drive without elevated permissions. See here.
Detect the folder permissions. It has to has write permission on the logged user.
Yes, it is permission error. You don't have enough rights to write file in C: drive. To write in these types of folder/drive you need admin permission.
You can give your application admin rights. Simple way is enforce your application to start in admin account/rights only. To achieve this
Solution Explorer -> your project -> Add new item (right click) -> Application Manifest File.
In this file change requestedExecutionLevel to
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
These enforce your application with admin rights only. On Windows 8/7/Vista it will display UAC (User Access Control) dialog box when you start the application.
Hope this will help you....