Anybody can help to reach exact path [duplicate] - c#

I have the code to save a file in a folder in directory
string timestamp = DateTime.Now.ToString("MM-dd-yyyy.HH-mm-ss");
var file = File.Create("Owe-Data.txt" + timestamp);
var com = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase + timestamp + #"\Data" + file;
MessageBox.Show(com);
if (!Directory.Exists(com))
{
Directory.CreateDirectory(com);
}
using (var sw = new StreamWriter(com))
{
sw.WriteLine(InputData);
}
}
i Displayed COM it gives path bt i cant see the Data folder or Owe-Data file at that path
Anybody can tell why this happening, or should i save the Data folder in current directory where this prgram running? bt i dnt know how to reach that path. Any solutions ??
Working on windows phone 5, visual studio 2008 .NET framwork 2.0

As per the Exceptions section of documentation,the above exception is thrown when
ArgumentException ------- folder is not a member of System.Environment.SpecialFolder.
It means the OS where you are running this command does not have Environment.SpecialFolder.CommonApplicationData as one of the special folder.
For knowledge,
Environment.SpecialFolder.ApplicationData is the most common one. This folder holds per-user, non-temporary application-specific data, other than user documents. A common example would be a settings or configuration file.
Environment.SpecialFolder.CommonApplicationData is similar, but shared across users. You could use this to store document templates, for instance.
Environment.SpecialFolder.LocalApplicationData is a non-roaming alternative for ApplicationData. As such, you'd never store important data there. However, because it's non-roaming it is a good location for temporary files, caches, etcetera. It's typically on a local disk.
I think the problem may be that Environment.SpecialFolder.CommonApplicationData is common and shared between different users and the user with which you have logged in is not having rights to access the folder or the Visual Studio has not been started in Admin mode.
EDIT Look at link and try to add a manual registry Common AppData defined in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\

Given you are asking about a .NET Windows Phone application as per the tags
I think your problem is that a .NET Windows Phone application does not have direct access to the file system; it can only access IsolatedStorage this is by design.
I would quote a Microsoft source for this but I can't seem to find one!
EDIT
See this article from MSDN

Related

where is the correct location for Data folder in developing process C# deskTop app

i write desktop app in C# .... this app will auto generate an C/C++ code for an embededd system project
so i have to copy some pre_writen drivers to the target folder (where the file is generated)
the problem is i don't know where i can correctly put the sourc driver in !!
for now i put the source driver in in the project foldr and i refrance it in my code lik
// projectfolder\bin\Debug\netcoreapp3.1\file.exe
string path = (Assembly.GetExecutingAssembly().Location);
DirectoryInfo exeDir = new DirectoryInfo(path);
DirectoryInfo projectDir = exeDir.Parent.Parent.Parent.Parent;
// now i can get the driver foler like this
string DriverPath = Path.Combine(projectDir.fullName,"drivers");
i guss that folder in the product level will be in C:\ProgramData
but for developing where the location shoud be in ?
In Windows there are different types of data that may be consumed by an Application such as
Application Properties
Application settings enable you to store application information dynamically. Settings allow you to store information on the client computer that should not be included in the application code.
Ex: Position, Font, Styles, User Configuration
File Type: App.Config(Is created at design time and is by default put into BIN folder) and User.Config (Created at run time)
Project > Add New Item > Installed > Visual C# Items > Application Configuration File
Application Data
Contains all the data, settings, and user files that are required by the installed software and UWP apps. These are user agnostic data.
Ex: Images, Resources, Sprites, Data Templates, txt files. It may also contain App.Config files
File Location: C:\ProgramData Environment.SpecialFolder.CommonAppData
User Data
Contain all data that is user specifc, such as his/her app specific settings.
Ex: Any type of data
File Location: C:\Users\[USERNAME]\AppData\Roaming Environment.SpecialFolder.AppData or Environment.SpecialFolder.MyDocuments
i guss that folder in the product level will be in C:\ProgramData but
for developing where the location shoud be in ?
yes, it will go to ProgramData, but during the development you can have it in your BIN folder or a directory of your choice if it matters
However most of the above will come into picture when you package your App to an MSI and bundle in all the dependency files and where they need to go.
EDIT
Based on the OPs clarification in comments, .CPP files will automatically go into the BIN/Debug Folder of your C# app.
You will need to dynamically place your device drives in the directory where your exe is running
To access the directory where your app is running :
string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location
Output of Path = Absolute path where your exe is running
C:\Users\User1\source\repos\Test\Test\bin\Debug\Test.exe
string exeDirectory = Path.GetDirectoryName(exePath);
The Directory path where your exe is situated
C:\Users\User1\source\repos\Test\Test\bin\Debug
The default location in a c# dekstop app in Environment.CurrentDirectory + "\\Folder"
This is mostly a question of how often the data will change. And how that will interact with the very strict management of write rights since NTFS became common (While the rule predates NTFS, with mostly FAT - and thus no rights to stop us - few programmers cared).
You can and even should put stuff into the Programm directory itself, if it does not change outside of Programm Updates/Reinstallations. If it only changes with a Installer or Updater - things that need administrative rights for their work anyway - it belong there.
If changes happen more often then that - especially stuff that can change at runtime or even needs to change at runtime - where the programm folder becomes unuseable. In this case the programm directory should at tops include a template file. Something you can copy to the real directory as a baseline, to have something to start working with. As for where to put this changeable data, look at the SpecialFolders Enumeration. The Userprofile - particulary Appdata folders are the point to look at. Wich specific one to use is a question of how you want it to interact with Domain Controler Synchronisation (Roaming vs non-Roaming user). Or if you want it to end up in Common.
Drivers sound like that rare case, where the programm directory is entirely fitting. Optionally you could have the drivers installed as a parallel application. Something that can be managed/updated seperately and is simply a requirement for your programm. Something that might be shared across multiple applications.

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.

Get access to program's own directory

this is a very simple issue.
Note: I am sure people have found and posted this same issue somewhere but I can't figure out the correct search terms to find it.
Okay, so here is my issue.
Let's say my program is stored at C:\Program Files (x86)\MyProgram\Program.exe.
Now in the program, it basically does
Directory.CreateDirectory(Application.StartUpPath + "\\Files")
So basically, this would create a directory called Files in the same folder as the program itself.
Assume that I have to create the folder in that location, so using a different location is not an option.
So the real problem is, if its located in the c:\Program Files directory, my program gets "access denied" when I try to create the folder.
So how can I get something like this to work without forcing the user to run it as an admin?
If it's in Windows 7, if UAC is elevate, you won't be able to modify anything in c:\Program Files without rooting yourself via 'run as administrator'.
And since windows is a multi-user operating system, storing anything user-specific there is a recipe for disaster.
The right place for your program to put its data is in the appropriate special folder, which you can get/create via either
// user-specific application data is stored here
string userSpecificAppDataDirectory = Environment.GetFolderPath(
SpecialFolder.ApplicationData ,
SpecialFolderOption.Create
) ;
// application data common to all users is stored here
string commonAppDataDirectory = Environment.GetFolderPath(
SpecialFolder.CommonApplicationData ,
SpecialFolderOption.Create
) ;
or one of the other Environment.GetFolderPath() overloads.
In modern operating system the folder C:\program files (x86) is write protected by the OS. You can't create sub folders here without using an administrative account (and also in that case you will be asked to confirm this action unless you disable UAC). So the correct way to follow is to create your data folder in another place. The best option is the CommonApplicationData folder extracted using:
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
or the SpecialFolder.ApplicationData enum if your data should be differentiated by the current user of the application, or the SpecialFolder.MyDocuments if these files are produced by your user and need to be opened freely by other programs (or need to be included in a backup)
After you get the special folder provided by the OS to store application data remember to create a subfolder for your application and the other subfolders as required by your requirements
// In Win7 this usually resolves to C:\ProgramData, but do not use this folder
string appCommon = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
// This resolves to C:\programdata\your_app_name\files
string appData = Path.Combine(appCommon, "your_app_name", "files");
// This will create all directories in the specified path one by one....
if(!Directory.Exists(appData)) Directory.CreateDirectory(appData);
You could try creating any files or folders you need during your installation procedure. I am not sure what success you would find if using a third party install creator, but my understanding is that items added via the Application Files... button in the Publish tab of the Project Properties section in Visual Studio then have access privileges kind of inherently granted for use by the application.

How do I refer to the directory where my .net program is installed?

I created a program in C# .net using VS2008.
When the user installs the program I don't know if it will be on the C: drive or D: drive or someplace else. The issue is that I need the program to automatically create files and then retrieve those files later on without any assistance from the user.
I thought the least complex situation was to place these files in the directory where the program is installed so that the location would remain constant and this strategy would reduce the chances that the files will be accidentally deleted by the user.
Question 1:
How to I refer to the install directory of my app when the user has their choice of the install location?
Question 2:
Should I even be doing it this way or should I be looking at this from a totally different perspective.
Assembly.GetExecutingAssembly().Location will give you the path to the currently executing assembly.
However, writing to that location will cause problems for users running on Vista, Server 2008 and later, which are more strict about normal users not writing to places like C:\Program Files. Your best bet is probably something like:
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
There are a bunch of options for Environment.SpecialFolder, based on what exactly you want to store.
Sounds like a perfect solution for the Isolated Storage function in .Net (System.IO.IsolatedStorage).
You access via objects and the path is controlled by .Net. It stores the items in the local settings\application data\isolated storage for each log in.
You can use the System.Environment.CurrentDirectory property to determine where your application belongs.
Alternatively, you could look into isolated storage. The data is stored on a user/machine basis (as you choose) so you can store different files for different users.
Which you choose depends on how much information you want to store, and the security surrounding it.
You can get the current directory using:
string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
This is a valid and useful way of storing files related to your .exe - you can always navigate using relative directories from where your executable is running from, meaning you don't need to worry about where it's installed.
Alternately, if you'd like your .exe to be freely copyable to any directory, you could consider storing your data in a well known location, like the user's Application Settings directory in their user profile (for windows).
Application.StartupPath should do that for you or:
private static string GetApplicationPath()
{
return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
}
How to get the path of app(without app.exe)?

Writing drive C: in Windows 7/Vista

I am developing an application that saves its settings in the install folder. If I install the app in the Program Files on drive C: and attempt to write the settings file I get an exception and that's it.
I know that the User Account Control (UAC) migth be the one that is not letting my app modify the content of the file.
I need help with the following issues:
Do the file editing in such a way that at least an UAC warning should be shown and if I answer yes the file becomes writable
If there is no way to edit the file on drive C: I need a method to store data somewhe
A more generic question would be:
How to create a C# program that after installing it to C:\Program Files\MyProgram under Windows Vista can manipulate (create/edit/delete) an .ini file in the installation directory? This file should be the same for all users.
Why don't you store the settings in a user-specific location like C:\Users\Username\AppData?
That way different users can have different settings on the same machine. Also, this is the recommended location for settings and the like.
Building on the answer from Ben S, check out the Environment.GetFolderPath method.
This method allows you to abstract away the specific location and just use a known SpecialFolder path instead (ie SpecialFolder.ApplicationData).
The fact that you are getting an exception means that your program is Vista/7 aware somehow. I am not totally sure what setting (in a C# project) triggers that. But if you can make your app 'pretend' it is an XP application, Vista will let it write to a shadow file located elsewhere.
But the proper way to get a writeable path shared by all users:
string path = Environment.GetFolderPath(
Environment.SpecialFolder.CommonApplicationData);
I'm surprised it hasn't been mentioned yet, but a viable C# option is to ditch INI files (yuck) and embrace the Settings facilities provided by .Net. They work very well across all Windows versions, they are directly supported by Visual Studio, and finally they are overridable at both the User and Machine level.
We've had no real problems to speak of utilizing this feature (this includes XCopy deployments, Installed applications, Citrix, etc).
Building on the answers of Ben S and akmad, you should put the ini file in the appDataFolder.
If you want the settings to be unique to each user, create an ini file for each user and put it in their AppData folder, which can be retrieved with the following code:
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
If you want the settings to be common to all users, but the ini file in the common AppData folder.
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)

Categories