0

While creating a folder / file is really easy, just last night I decided to test my application on a different computer.

In that application I do create a specific directory. As I expected on the different computer it didn't quite work.

A file path in windows looks like this C:\Users\YOUR-USERNAME\Documents\Dreams.

How thought in the code would you cope with the fact that on a new computer the username and drive partition could be different (a drive partition is the letter at the very begging for example C: in this case).

I am really confused on how a programmer would get around drive partitions and usernames.

Thanks, any help is very much appreciated.

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
  • 1
    It would help to see your code. I assume you hardcode the absolute path, which you should never do. Usually you use relative paths or special paths like AppData, see [C# getting the path of %AppData%](http://stackoverflow.com/questions/867485/c-sharp-getting-the-path-of-appdata). – CodeCaster Jan 31 '15 at 14:43
  • @Steve : I'm not sure that this is a dupe of "current user directory". OP wants "Documents", and assuming that it's `%USERPROFILE%\Documents` isn't necessarily true. OP is specifically looking for `Environment.SpecialFolder.MyDocuments`. I couldn't find a dupe for this... – spender Jan 31 '15 at 15:16

3 Answers3

1

This should provide path to the users 'MyDocuments' folder

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

The Environment.SpecialFolder enum has a list of other folders that may be useful to you.

Kevin Brady
  • 1,684
  • 17
  • 30
0

Good Windows software doesn't make assumptions about such things. It finds out at runtime what is possible and good by asking Windows (special folders, enumerating directories and files, looking in the registry), by asking the user (but still checking with Windows, as encapsulated in file/folder browser dialogues) or by using isolated storage.

arbitrary
  • 103
  • 9
0

You have to check if folder exists or not also. It work's on .Net Framework 4.0 and higher.

     string path = Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); 

       bool flag = System.IO.Directory.Exists(path);

        if (!flag)
        {
            System.IO.Directory.CreateDirectory(path);
        }
Binamra
  • 105
  • 1
  • 4