Currently writing software which needs to store data (I know, it's that advanced) but I don't know where people are going to want to save it. As a default I would like it to save to C:\ but that doesn't work for use on my server which uses N:\ as the default drive.
I could change it to use N:\ but I would have the same problem if a person the chose to run it on a system with anything else as a drive.
I know you can get the current programs location, but how could I then copy the first part so I could use it.
Example
Program location: X:\Something\Something\program.exe
What I want to be able to take from that: X:\Something\Something and the add the name of the new files to be created (newdatafile.txt) so it becomes X:\Something\Something\newdatafile.txt
I'w working in C#.
I think this will do what you asked for:
var exeFolder = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + #"\";
Then simply append your new file name to the end.
You can use the SaveFileDialog to handle all the heavy lifting.
https://msdn.microsoft.com/en-us/library/sfezx97z(v=vs.110).aspx
Related
I want to save my Files in a more generic way than on Desktop.
So i want to create my own Subfolder in Programs Folder, which i can use to save my stuff.
But i get "System.UnauthorizedAccessException" if i try to create a File using File.AppendAllText(#"C:\Program Files\MySubfolder\MyFile.txt,someString);
I even disabled the Protection of the Folders manually.
My App is not yet compiled so i cant run it as administrator, can i?
How does every Program use this Folder but i cant?
Do i need to compile my App everytime i make a small change and want to test it?
I would really apreciate Help since im stuck with that multiple hours now
It is a very bad practice to try to write in Program Files. This folder as well as other sensitive folders are protected by the OS to prevent malicious code hide between your programs or to prevent unsavy users from messing on the installed programs.
If you want to write your private stuff on your disk you can use these folders
string folder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string myFolder = Path.Combine(folder, "MyReservedPath");
Directory.CreateDirectory(myFolder); // if exists does nothing
string myFile = Path.Combine(myFolder, "MyPrivateData.txt");
File.WriteAllText(myFile, dataToWriteOnDisk);
The CommonApplicationData resolves to C:\programdata and this place is usually used to store information needed by your program for any user that uses it.
If you want to store some data that your program produces then it is better to use the
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
There are many other places available, just look at the Environment.SpecialFolder enum.
This code will give you a list of everything mapped to the actual folders in your system
foreach (Environment.SpecialFolder x in Enum.GetValues(typeof(Environment.SpecialFolder)))
Console.WriteLine($"{x} = {Environment.GetFolderPath(x)}");
I used below code to get the user's AppData folder -
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
But what I got is "C:\Users\(users)\AppData\Roaming". Is there a way to only get "C:\Users\(users)\AppData"?
First of all, accessing that folder directly is probably not a good idea unless Microsoft has published an API to retrieve its location. This means that there are no guarantees that this folder will even exist.
If you for some reason really want to retrieve this folder, you could probably do something along the lines of
Directory.GetParent(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData))
Then to verify, you could also retrieve e.g.
Directory.GetParent(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData))
If the two are the same, it is likely the folder you want to find.
But again, it is probably a good idea to question the motivation on why you need this path in the first place.
Is this what you are looking for
first get the user name from Environment object.
string userName = Environment.UserName;
then, use that User Name for generating the path.
string path = $"C:\\Users\\{userName}\\AppData";
I am relatively new to C#, however I do have some basic knowledge of code from courses in high school and university. However, there is one thing I have not been able to figure out over the years. I am currently making a Form Application for a database system that stores information in a List using Visual Studios 2010.
On my main form; when the save button is pressed, the information is then serialized into an XML file. When the information is loaded, the information is then deserialized and put into the List for use in the code. All this is working correctly.
This process of saving and loading is done based on a string which contains the file path. This string is the location of a folder on my desktop (I put it there for easy access), and I am able to change the string in the code to basically move where the information is stored.
However, I have a separate "Admin" form which is able to change this file path string. When the user clicks the button to change the file path, I get the input from a text box, check its formatting, move the current file to the new location and update the location for the save method so changes can be saved before the program is closed. From there, the program reacts the same way as if I had changed the string from inside the code.
The problem occurs when I close the program. I do not know how to tell the program when it runs again that the location has been changed from the default and look for the file in the new location. The program reacts just like the file was missing (like it should) when it looks in the default location.
So basically, how do I tell the program that the save location was changed from when it was last run so it knows to load the info from a new location?
I have tried looking for an answer since high school (about 2 years ago) and have not found a solution. As a result I usually just keep the save location as the default (which I set it to) and don't try to change it. But this time, its important that the save location can be customized. My experience with Visual Studios is limited, as everything I know is from messing around with the program and looking up stuff when needed.
If needed, I can post snippets of my code. Thank you in advance!
It seems like what you really want is to save some user-defined settings for recall at run-time. Here is a MSDN link describing some basic conventions for storing / retrieving these settings.
https://msdn.microsoft.com/en-us/library/bb397750(v=vs.110).aspx
A *.config file would suffice (depending on the scale of the application).
Otherwise, you may want to go down the route of storing these settings in a database (if the scale is rather large, or if user-authentication is required for the application).
Here is another previous question dealing with this same subject (regarding App.config files):
What is App.config in C#.NET? How to use it?
I recommend using a config file where the .exe is, and write the location there, then read it in on program startup.
In particular .net provides this class which can manage your config file for you (assuming you have an app.config in your solution, otherwise create one)
https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings(v=vs.110).aspx
If i make the call File myFile = new File('myfile.txt'); where is does this get saved to?
It's relative to the process's current directory. What that is will depend on how your application has been started, and what else you've done - for example, some things like the choose file dialog can change the current working directory.
EDIT: If you're after a temporary file, Path.GetTempFileName() is probably what you're after. You can get the temp folder with Path.GetTempPath().
That won't compile.
EDIT: However, if you're after where creating a text file using StreamWriter or File.Create("text.txt"), etc, then I defer to the other answers above; where it will be where the application is running from. Be aware as others mentioned that if you're working out of debug it will be in the debug folder, etc.
NORMALLY it gets saved to the same directory the executable is running in. I've seen exceptions. (I can't remember the specifics, but it threw me for a loop. I seem to recall it being when it's run as a scheduled task, or if it's run from a shortcut.
The only reliable way to know where it is going to save if you are using the code snippet you provided is to check the value of System.Environment.CurrentDirectory. Better yet, explicitly state the path where you want it to save.
Edit - added
I know this is a bit late in modifying this question, but I found a better answer to the problem of ensuring that you always save the file to the correct location, relative to the executable. The accepted answer there is worth up-votes, and is probably relevant to your question.
See here: Should I use AppDomain.CurrentDomain.BaseDirectory or System.Environment.CurrentDirectory?
I am by no means a programmer but currently am wondering if an application creates a temp file that windows names. For example the file it creates is tmp001, is there a way i can take that name tmp001 and ask windows to give me the next temp file it would create before it creates it.
Thanks,
Mike
There is no direct means to get to know the next temporary filename to be created.
For example, programmers use the System.IO.Path.GetTempFileName method, but one can add application-specific prefixes or suffixes in order to make it easier for the application to find its newly created files.
One can even choose to save this temporary file elsewhere than the system Temp folder.
You would need to define a "temp file" much more explicitly in order to answer this question with a "Yes". The problem is that a "temp file" is just something not meant to be kept. It could exist anywhere on the system and be created by a user, application, or service. This would make it nearly (or actually) impossible to answer your question with a "Yes".
If you constrain the definition of a temp file to just the files in the official temp folder (or a subfolder), you still have a problem if you're trying to catch names not generated by windows. Any app could produce a particularly named temp file in that folder, without Windows caring.
If you further constrain the definition to be only those files named by Windows, you might be able to get somewhere. But, does that really meet your needs?
After all of that, maybe it would be better to describe the problem you're trying to solve. There may be a much better (workable) solution that would address the issue.
Typically applications use the Win32 API GetTempFileName to get the temporary directory.
The process of how the temp file is generated is described there.
I'm not sure why you want this info, but perhaps you could for example register for directory changes via a Win32 API like ReadDirectoryChangesW or by using a mini filter driver.
This kind of code just cannot work reliably on a multi-tasking operating system. Another thread in another process might pre-empt yours and claim the file name you are hoping to create.
This is otherwise easy enough to work around, just name your own files instead of relying on Windows doing it for you. Do so in the AppData folder so you'll minimize the risk of another process messing it up.