Write file in C:\ drive permission issue [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i have developed a win application with c# which generate file in a folder in c:\ drive. when try to generate file there then problem occur for permission issue but when the application generate file in other drive than C:\ then no problem occur. so when i will distribute my apps setup to end user then i wont be sure that user who will install my apps does has the permission to generate file in C:\ drive.
so guide me how can i overcome this issue. should i Using Manifests to Elevate an application in win OS?
i got some article
http://blogs.msdn.com/b/nikhiln/archive/2007/04/19/embed-a-manifest-to-make-an-application-elevate-in-vista.aspx
http://www.codeproject.com/Articles/105506/Getting-Elevated-Privileges-on-Demand-using-C
http://archive.msdn.microsoft.com/KB981778
etc......please guide me with right knowledge. thanks

You can start your application again with elevated permission and have some check at the application's start to see if this is the case. Here's an example: (Be careful not to get into an endless loop of the application starting itself.)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1 && args[1] == "-e") Text = "Elevated";
}
private void button1_Click(object sender, EventArgs e)
{
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = Application.ExecutablePath,
Arguments = "-e",
Verb = "runas",//-Admin.
}
};
process.Start();
}
}
I agree, though, that storing information in "C:" is probably not a good idea. You can try someplace like: Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).

Related

The target path "" is a directory and not a file [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to copy a file into another folder, here is my code.
private static void CopyDirectory(DirectoryInfo source, DirectoryInfo target)
{
foreach (var sourceFilePath in Directory.GetFiles(source.FullName))
{
FileInfo file;
if(IsAccesable(sourceFilePath, out file))
{
file.CopyTo(target.FullName); //ERROR HERE
}
else
{
//DO WORKAROUND
}
}
foreach(var sourceSubDirectoryPath in Directory.GetDirectories(source.FullName))
{
DirectoryInfo directory;
if(IsAccesable(sourceSubDirectoryPath, out directory))
{
var targetSubDictionary = target.CreateSubdirectory(Path.Combine(target.FullName, sourceSubDirectoryPath));
CopyDirectory(directory, targetSubDictionary);
}
else
{
//DO WORKAROUND
}
}
}
I keep getting the error message: The target path "" is a directory and not a file
Full sourcePath:
"c:\\Hypixel Bots Interface\\.gitattributes"
Full targetPath:
"C:\\Users\\wout\\source\\repos\\FileCloner\\FileCloner\\bin\\Debug\\net5.0\\Target\\Hypixel Bots Interface"
There is no file in your path. For example, create a file in your folder and name it test.txt an run again your code to verify if the error will disappear.
"C:\Users\wout\source\repos\FileCloner\FileCloner\bin\Debug\net5.0\Target\Hypixel Bots Interface\.gitattributes\test.txt"
As the error says, you want the targetPath to be a file name. You are just pointing to a folder.
"C:\\Users\\wout\\source\\repos\\FileCloner\\FileCloner\\bin\\Debug\\net5.0\\Target\\Hypixel Bots Interface\\.gitattributes"
That would be pointing to a new file in that directory

How to delete a directory path that is giving a access denied error [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Improve this question
Bit of backstory into what I am accomplishing I work as an installation tech for Autodesk and I thought it would be fun to create a simple program to help automate the process of clearing out folders normally left behind after the software is uninstalled.
The directories that I am trying to delete are as followed.
C:\ProgramData\FLEXnet
C:\Program Files\Autodesk\
C:\ProgramData\Autodesk\
C:\Program Files (x86)\Autodesk\
C:\Users\All Users\Autodesk\
C:\Users\**YOUR USERID**\AppData\Roaming\Autodesk\
C:\Users\**YOUR USERID**\AppData\Local\Autodesk\
This is the code that I have been toying arround with
private void btn_start_Click(object sender, EventArgs e)
{
//di.Attributes &= ~FileAttributes.ReadOnly;
try
{
File.SetAttributes("C:/Program Files (x86)/Autodesk", FileAttributes.Normal);
Directory.Delete("C:/Program Files (x86)/Autodesk", true);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
try
{
File.SetAttributes("C:/ProgramData/Autodesk", FileAttributes.Normal);
Directory.Delete("C:/ProgramData/Autodesk", true);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
For the following line it get this error.
File.SetAttributes("C:/Program Files (x86)/Autodesk", FileAttributes.Normal);
System.UnauthorizedAccessException: 'Access to the path 'C:\Program Files (x86)\Autodesk' is denied.'
If I where to remove that line and use the Directoyr.Delete on it's own I would get this error instead.
System.UnauthorizedAccessException: 'Access to the path 'AcIPC_2_x86.dll' is denied.'
I spend a couple of days poking around trying to figure out how I may allow the software the ability to delete the directories but I feel that i'm at an impasse.
Try running the application as administrator through the code, it might be worth a try:
Add a new item to your project folder and call it "Application Manifest File". Then procceed to change this line of code <requestedExecutionLevel> to this:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
This will prompt the user to allow administrator access (So essentially the same as right clicking on it and click run as administrator)
I don't know that this isn't the right place for you. There are reasons why you can get ACCESS_DENIED that can be programmatically overcome. Keep in mind that unless you are an administrator, you cannot remove files or folders from various directories, including Programs and Programs (x86). As fluffy said, you can run as an administrator (if you are an administrator) explicitly because the natural state of an application is to run non-elevated. Here is an example of how I have overcome this problem:
public static class FileSystem
{
public static void RunAsAdministrator(this Process process,
string arguments = "")
{
if (process == null)
{
throw new ArgumentNullException(nameof(process));
}
ProcessStartInfo startInfo = new
ProcessStartInfo(process.MainModule.FileName)
{
Verb = #"runas",
Arguments = arguments
};
Process.Start(startInfo);
public static void TakeOwnership(string path)
{
if (AppDomain.CurrentDomain.IsAdministrator())
{
using (new PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.TakeOwnership))
{
DirectoryInfo directoryInfo = new DirectoryInfo(path);
DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
if (directorySecurity == null)
{
return;
}
directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);
Directory.SetAccessControl(path, directorySecurity);
}
}
else
{
Process.GetCurrentProcess().RunAsAdministrator();
}
}
}
public static bool IsAdministrator(this AppDomain threadDomain)
{
threadDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal currentPrincipal = (WindowsPrincipal) Thread.CurrentPrincipal;
if (currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator) || currentPrincipal.IsInRole((int) WellKnownSidType.AccountDomainAdminsSid))
{
return true;
}
using (WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent())
{
return windowsIdentity.Groups?.Any(windowsIdentityGroup => windowsIdentityGroup.Value.Equals(#"S-1-5-32-544")
|| windowsIdentityGroup.Value.EndsWith(#"500")
|| windowsIdentityGroup.Value.EndsWith(#"512")) == true;
}
}
}
If you are already running as an administrator, you can take ownership of the directory immediately, otherwise, there is code include to restart the current process in elevated mode.
I CAUTION YOU THAT DOING IS AT YOUR OWN RISK. Taking ownership is a big deal. The other option is to take a less sledge-hammer approach and modify the ACL on the directory or file(s).
The PrivilegeEnabler code is useful regardless. It can be found here.

Store data in C# application [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a message prompting the user to upgrade some equipment connected to the computer. I want to let the user disable this message in the future, by checking a box before pressing cancel.
How can I store this user option, so that next time the program executes I can avoid showing this message based on the user choice made in the last session of the application?
The two cleanest ways are the Registry and User Settings.
I prefer User Settings because:
they're in XML (no registry hacking required)
a lot of the grunt work is done by the framework
User settings persist across upgrades automatically with ClickOnce
All you need to do is go to the Setings tab in the project's properties, add a setting, and set it's type to User.
Then just save the settings after changing them:
Properties.Settings.Default.ShowDisconnectMessage = false;
Properties.Settings.Default.Save();
The registry works similarly but it requires a bit more code and is not strongly-typed:
RegistryKey key = Registry.CurrentUser.OpenSubKey("Software",true);
Key = key.OpenSubKey("AppName", true);
key.SetValue("ShowDisconnectMessage ", "false");
You'll need to make the messages in your application use a custom form. That form will need to show the message as well as have the check box. Then you'll want to store that information somewhere. I'm going to say in the application configuration file.
So, to save the data in the configuration file, first build a few extension methods to make it easier:
public static class Extensions
{
public static void SetValue(this KeyValueConfigurationCollection o,
string key,
string val)
{
if (!o.AllKeys.Contains(key)) { o.Add(key, val); }
else { o[key].Value = val; }
}
public static string GetValue(this NameValueCollection o,
string key,
object defaultVal = null)
{
if (!o.AllKeys.Contains(key)) { return Convert.ToString(defaultVal); }
return o[key];
}
}
Then, when you want to read that value to determine if you ought to show the message, do this:
var val = (bool)ConfigurationManager.AppSettings.GetValue("ShowTheMessage");
and then when you want to save the value, do this:
var config = ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
var app = config.AppSettings.Settings;
app.SetValue("ShowTheMessage", checkBox.Checked);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

How can I load kongregate chat in my webbrowser? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have a simple program, and I am trying to load the kongregate chat into a WebBrowser, but it is not working...
When I first start it up, it navigates to a game, and then it gives me 4 Script Error, and the chat just sits there saying: "Joining room...". I don't think it is a problem with the browser settings, because it works on internet explorer. Is there something that is messed up with my WebBrowser? I have let it sit there for a few minutes, and it still does not work. I have set the suppressScriptErrors to true and false, and it still does not fix it.
FYI: I am not doing anything bad with my program, like cheating, or spamming, or anything like that, I just want the webpage to show up, and sometimes I like to be able to have things copied, so I put a few TextBoxes to the right of it, so I can paste it into chat, if I won't to post a few things...
This article has the solution to your problem. It appears that the WebBrowser control in Visual Studio launches in IE7 mode by default. That's why you get javescript errors with the control but, not in your browser. I highly suggest you read the article linked that the top. Luckily, there is a fix. The following code was taken from another stackoverflow answer to a question that indirectly addresses your issue. Here is that link, and here is the code.
string installkey = #"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION";
string entryLabel = Path.GetFileName(Application.ExecutablePath);
System.OperatingSystem osInfo = System.Environment.OSVersion;
string version = osInfo.Version.Major.ToString() + '.' + osInfo.Version.Minor.ToString();
uint editFlag = (uint)((version == "6.2") ? 0x2710 : 0x2328); // 6.2 = Windows 8 and therefore IE10
RegistryKey existingSubKey = Registry.LocalMachine.OpenSubKey(installkey, false); // readonly key
if (existingSubKey == null) {
existingSubKey = Registry.LocalMachine.CreateSubKey(installkey, RegistryKeyPermissionCheck.Default); // readonly key
}
if (existingSubKey.GetValue(entryLabel) == null) {
existingSubKey = Registry.LocalMachine.OpenSubKey(installkey, true); // writable key
existingSubKey.SetValue(entryLabel, unchecked((int)editFlag), RegistryValueKind.DWord);
}
Also, the article I mentioned up top says that you should create an entry for the VS host process for your app too or it won't work in debug mode. Good luck and I hope this solves your issue!

How can i run bat file i just added to the resources in my project properties? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I went to my project > properties > resources > add existing file > test.bat
Now i have this code :
private void Information()
{
}
I call this function from a button click event.
I want to execute the bat file, so every user which will use my program will be able to execute the bat file directly from the program.
The bat file just create dxdiag.txt in a specific directory.
How can i do that?
You can put the batch file into the executable file folder and then use the Process class like this:
System.Diagnostics.Process.Start(System.IO.Path.Combine(Application.StartupPath, yourBatFileName));
Pay attention that usually your solution is compiled into the Debug folder or into the Release folder depending on your configuration (so you have to put the file in the correct one).
Use this class
Process.Start Method
You can use the following for parameters...
var myProg = new System.Diagnostics.Process();
myProg .StartInfo.FileName = "file name with full path";
myProg .StartInfo.UseShellExecute = false;
myProg .StartInfo.Arguments = "";
myProg .StartInfo.RedirectStandardOutput = true;
myProg .StartInfo.CreateNoWindow = true;
myProg .Start();
myProg .StandardOutput.ReadToEnd().Dump();

Categories

Resources