简体   繁体   中英

Relative paths in programs running in Debug Mode[VS2010]

I'm debugging a program right now in visual C#, and in the program I access a file using a relative path.

  Stream s = File.Open("usr.dat", FileMode.OpenOrCreate);

This is currently spitting it out in the (Project Folder)/bin/x86/Debug folder(where the compiled executable is). Is there a way to change where the relative path opens out to?

(The reason I'd want to do this is because I have multiple projects yet I'd want to have the file usr.dat be accessible to all of them, so if you have another solution to this I'll gladly take it).

EDIT: I found that I can simply change the projects working directory in the properties. Thanks for the input, guys

Yes, you cannot leave it like this. This will fail when you deploy your program on a machine that has UAC enabled or runs with a non-admin user account. You won't have write privileges to the directory in which your EXE is stored.

Review Environment.GetFolderPath() to find one of the appdata folders that you'll have write access to.

Don't use the "current directory" - this is a 1980's approach and it's easily broken (eg if you use a file open dialog, the user can leave the current directory anywhere, the user can change the current directory when lanching your application, etc.).

So, to find out where to start from, you could use Application.StartupPath.

In Vista/Win7, you can't/shouldn't write anywhere in Program Files - therefore, only use a path relative to your .exe if it is to a read-only file. In this case, you could install your programs into "Program Files\\MyCompany\\ApplicationName" and install the shared files into "Program Files\\MyCompany\\Shared", and use Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(Application.StartupPath)), "Shared") as the folder to read shared files from.

If you wish to write to the file, then you should use the user's My Documents folder (for data visible to the user), or the Application Data folder (for internal data you wish to "hide" from the user). Use Environment.GetFolderPath() to access these paths (eg Environment.SpecialFolder.ApplicationData, etc)

The EXE's current location is being used as the default path for the file you are working on because you only specified the file name. If you use a file path (a string containing the complete folder hierarchy) before the file name, it should do the trick.

You might want to save the path as a separate string variable and concatenate it with the file name. Separating the path into a variable would also help you verify it in File functions like File.Exists("path\\to\\your\\file\\file.ext")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM