I created a WinForms application that includes code to find the user's desktop and perform 3 tasks:
1. Create a folder
2. Read a .csv file
3. Output some data to a .csv file on the desktop.
I'm using the code below to find the user's desktop
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
I used the ClickOnce deployment to install the program to our network drive. The program installs successfully, but Whenever I have someone attempt to run the program from their terminal, they get an error message that states "The directory name is invalid" and it references my desktop and not the user's.
How should I change my code or the deployment method so it references the user's desktop?
If directory invalid try creating it
Try with this code
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string extension = ".log"; filePath += #"\Error Log\" + extension;
if (!Directory.Exists(filePath)) {
Directory.CreateDirectory(filePath);
}
I made the following change to my code and it worked as needed:
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
Related
I have C# wpf installation done with .net using click once installation. All works fine. Then I have the following code which is part of the installed program:
String destinationPath = System.Windows.Forms.Application.StartupPath + "\\" + fileName;
File.Copy(path, destinationPath, true);
this.DialogResult = true;
this.Close();
But I get this error:
System.UnauthorizedAccessException: Access to the path C:\user\pc\appdata\local\apps\2.0....... is denied.
at System.IO.File.InternalCopy(String sourceFileName, String destFileName, Boolean overwrite, Boolean checkHost)
at System.IO.File.Copy(String sourceFileName, String destFileName, Boolean overwrite)
Is it a permission error or do I need to tweak something in my code?
What puzzles me is why the user is able to install the program using click once into that directory without any issues, but uploading a file to it doesn't work?
When installing an application the installer usually asks for administrative privileges. If the user chooses "Yes" the program will run and have read and write access to a larger variety of paths than what a normal user has. If the case is such that the installer did not ask for administrative privileges, it might just be that ClickOnce automatically runs under some sort of elevated privileges.
I'd suggest you write to the local appdata folder instead, but if you feel you really want to write to the very same directory as your application you must first run your app with administrator privileges.
To make your application always ask for administrator privileges you can modify your app's manifest file and set the requestedExecutionLevel tag's level attribute to requireAdministrator:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
You can read a bit more in How do I force my .NET application to run as administrator?
I was running a program that would generate file. The destination folder was read only. And it would crash with the error. Removing the read-only attribute using folder properties resolved the error.
First, if you need to write any data you should use the Environment.SpecialFolder enumeration.
Second, do not write to any folder where the application is deployed because it is usually read only for applications. You probably want to write to the ApplicationData or LocalApplicationData enumerations.
I think that access to %appdata% is restricted by default on windows 8 (or 7) onwards.
When the app installed via ClickOnce you are probably prompted to give it permission to alter this computer - is that right?
You can try running the app with admin permissions as a test (hold shift, right click the .exe, run as administrator) which will probably solve it, but it's not an ideal way to do it.
Instead try another folder, something like:
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
or
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments )
which should give you better luck.
As a side note - if you are building paths in code, rather than using
path + "\\" + path + "\\" + filename
which is prone to failure (path may already have a \ on the end) it is usually better to use Path.Combine(..)
String destinationPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), fileName);
In my case, the remote server was returning "." and ".." when I was trying to download (SFTP) files and write to our local/network folder. I'd to explicitly discard the "." and ".." file names.
I want to be able to set default folder and file creating inside of the folder where the app is installed? Because this app will be used on multiple machines so I cannot specify path like C://Users/PcName/etc.. Is there any very simple way of doing it?
What you are trying to do is not advisable; if your application is installed using recommended default methods (following Microsoft guidelines) the app will be in a directory under C:\Program Files (or where the program files folder may be redirected) and the user that runs the app will not have write access to that directory, so the directory creation will fail.
That said, you cannot use the Environment.CurrentDirectory, because it may or may not be the directory where your application's executable files reside, neither CurrentDomain.BaseDirectory, because that is not significative too (documentation says it's the directory where the loader will search for assemblies, but that may or may not be the directory of your application's executable files).
Copying from this other answer, the correct way to find the directory of your assembly is
public static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
Once you have the path, you can try to create the directory with System.IO.Directory.CreateDirectory() and a file with System.IO.File.WriteAllText() or its siblings, or any other standard method of creating files.
You may also want to use the newer Assembly.GetExecutingAssembly().Location property, and use Path.GetDirectoryName() on that.
This applies to both web and windows apps:
Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
You can get the path for the executable using this code (most of the time, actually it returns the current working directory)
System.Environment.CurrentDirectory
If you only specify a path that doesn't start with a drive letter then the path will be relative to where the application is running. e.g. The following program will create a folder and file in the application's local folder.
class Program
{
static void Main(string[] args)
{
var installedLocation = Directory.GetParent(Assembly.GetExecutingAssembly().Location);
var di = installedLocation.CreateSubdirectory("MyFolder");
File.WriteAllText(Path.Combine(di.FullName, "File.txt"), "This will be written to the file");
var installedPath = AppDomain.CurrentDomain.BaseDirectory;
var di2 = Directory.CreateDirectory(Path.Combine(installedPath, "MyFolder2"));
File.WriteAllText(Path.Combine(di.FullName, "File2.txt"), "This will be written to the file");
}
}
I have 3 application (asp.net website, console application, SSIS) and a common class library which is used by all these 3 application. That common library fetch the external configuration file which is located in the the current running directory. For example
ASP.NET - > c:\MySite\appconfig.xml
CONSOLE -> C:\MyConsoleApplication\appconfig.xml
SSIS -> c:\MySSISPakage\appconfig.xml
I used the following code to fetch the current running application path to fetch the appconfig.xml file
string appPath = AppDomain.CurrentDomain.BaseDirectory;
In the web application it is running file and returning the path
c:\MySite.
But in the console application it is return the path
C:\MyConsoleApplication\bin\debug
. I need to fetch the path
C:\MyConsoleApplication
for the console application. Any idea?
You can Find Parent Directory using Directory.GetParent
try like this:
Program is name of any class in your project
string path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(Program)).Location);
Console.WriteLine(Directory.GetParent(Directory.GetParent(path).ToString()).ToString());
I have setup my sqlite database path as
string AppPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
dbName = AppPath + "\\data\\rbssystems.sqlite";
But when application is packed and installed using setup, my application uses
C:\Users\<username>\AppData\Local\VirtualStore\Program Files\RBS\data
it should be using
C:\Program Files\RBS\data
Can anyone tell whats going around and how to make it read database from
C:\Program Files\RBS\data
Thanks
Your app can't write to C:\Program Files unless it has administrative privileges. Windows automatically redirects you to C:\Users\<username>\AppData\Local\VirtualStore\Program Files instead. See this article for the explanation: http://blogs.windows.com/windows/archive/b/developers/archive/2009/08/04/user-account-control-data-redirection.aspx
Application data should always be in the AppData folder, never in Program Files.
In Windows using C#, how can I get the installation path of a software (for example consider NUnit or any other software like MS word, etc.) from my project? Also how to set the path variables that we set in Environment variables so that we can run the application just by giving in command prompt.
Like if I install NUnit in "C:\Program Files" I can run it by giving 'NUnit' in cmd prompt but if I install in a different location I can't do the same.
I need to get the location or path of NUnit or any other software installed in my system (having Windows XP) from my project.
EDIT:
Like I can get the path of installed program from registry.
HKEY_CURRENT_USER->SOFTWARE
Use the system and application classes. This will give you all sorts of information.
EG: Application.ExecutablePath
It also provides methods to do what you want to.
Edit: Also see registry read/write instructions here:
http://www.c-sharpcorner.com/UploadFile/sushmita_kumari/RegistryKeys102082006061720AM/RegistryKeys1.aspx?ArticleID=0ce07333-c9ab-4a6a-bc5d-44ea2523e232
Application.ExecutablePath (includes filename)
Application.StartupPath (not includes filename)
This will give you the path where the application started. Hopefully it will be the installation path.
string appFileName = Environment.GetCommandLineArgs()[0];
will give you the full path of the executable and
string directory = Path.GetDirectoryName(appFileName);
extracts the directory.
string envPath = Environment.GetEnvironmentVariable("PATH");
Environment.SetEnvironmentVariable(envPath + ";" + yourPath);
edits the PATH environment variable for the current process.
Application.StartupPath is used to get installation location in c#.
Like if i install Nunit in "C:\Program
Files" i can run it by giving 'nunit'
in cmd prompt but if i install in a
different location i cant do the same.
May be you are using Windows Vista, which can search in Program Files, but won't look in other folders.
In windows using C#, how to get the
installation path of a software(for
example consider nunit).?
It depends, how you are installing the application. The installer knows the path, you may program the installer to write that path to somewhere, say registry.
Also how to set the path variables
that we set in Environment variables
so that we can run the application
just by giving in command prompt.
How do I get and set Environment variables in C#?
Steps to extract value from registry are shown in following code snippet.
You may already know that there are no standard rules for applications to place their installation info.
The steps shown below are for COM based applications where the appplication must provide Local executable path in a reasonably standard manner.
For non-com applications, check to see if some data can be extracted from installed applications cache.
I hate to admit that the solution is not as elegant as I want it to be. Each subkey has to opened in series and opening in single method does not work.
//string hiveName = #"CLSID"; // for 64 bit COM 7applications
string hiveName = #"WOW6432Node\CLSID"; // for 32 bit COM applications
using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(hiveName))
{
if (key != null) {
using (RegistryKey key2 = key.OpenSubKey("{<YourAppGUID>}"))
{
if (key2 != null) {
using (RegistryKey key3 = key2.OpenSubKey("LocalServer32"))
{
if (key3 != null) {
return key3.GetValue("").ToString();
}
}