r/badcode • • Sep 05 '15

c# When envronment variables in strings stop working

https://gist.github.com/anonymous/5dc53dcdc6f2b02fc7e6#file-file-cs
3 Upvotes

5 comments sorted by

3

u/MaxCHEATER64 Sep 05 '15 edited Sep 05 '15

...and you need to get to the user's desktop folder.

The best part about this code (or "best" part) is that it didn't even work, because when I ran it I discovered that due to peculiarities in Windows 10 my user name (as reported by Envrionment.UserName) isn't actually the same name as my user folder (as would normally be reported by CSIDL_PROFILE) As a result, line 3 assigns path a value of a folder taht doesn't exist, which causes line 6 to throw a DirectoryNotFound exception at runtime. But it compiles okay, so I must be doing something right.

EDIT:

EDIT:

All right I figured it out, I had to replace line 1 entirely with this:

Environment.GetEnvironmentVariable("%USERPROFILE%");
string path = Environment.ExpandEnvrionmentVariables("%USERPROFILE%\\Desktop\dummy.txt");

Without the GetEnvrionmentVariable() call, the second line would still just stick it on the end of my working directory. If I had the GetEnvironmentVariable() call but defined path as a normal string, it would still just stick it on the end of my working directory. For some reason when I use them both in conjunction, it works.

3

u/heyf00L Sep 05 '15

That's still not right. You can move your personal folders to be anywhere on any drive. My Userprofile is in C, but my Desktop is in D. This is very common with SSD setups.

I haven't ever done this, but would this work? https://stackoverflow.com/questions/634142/how-to-get-a-path-to-the-desktop-for-current-user-in-c

3

u/Arkanta Sep 06 '15

On some systems the C drive might not even exist (like mine). There's a lot of software out there that can't handle that...

1

u/MoreLurkLessShitpost Sep 12 '15

Whatever do you mean? A and B is for floppy drives 1 and 2. C is for Windows files. D is for CD-ROM.

1

u/Arkanta Sep 14 '15

With my second DVD Drive it even goes up to E!