Click here to Skip to main content
Click here to Skip to main content

Using `Environment.SpecialFolder` to Maximize Portability

, 26 Jun 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
How to avoid some hardcoded paths with the uses of Environment.UserName

Introduction

Assumptions

  • You're reading or writing to a file on your computer (in some folder under your user folders, my documents, desktop, etc.), and using some code that looks like:
    // Path to the file you want to read:
    var path = "C:\Users\Your.User.Name\Documents\LINQPad Queries\Misc Files\parse_me.txt";
    
    // Happily read your file content:
    string[] read_all_lines = System.IO.File.ReadAllLines(path);
  • You're familiar with Linqpad or Visual Studio.
  • You work on 2 different computers. For ease of reference, let's call them Home and Work .
  • You have a file on your Home Desktop, and you want to continue working from Work.
  • You've copied your linqpad query and your Home desktop file to your Work desktop

Following those assumptions, you try to run your query on your Work computer, and realize it fails to work, because the paths are all messed up.

In my case, I keep all my linqpad queries in my documents folder, under the default LINQPad Queries folder. In that folder, I have a "Misc files" folder with some text files I was trying to parse, let's assume it's parse_me.txt.

First, linqpad is being run from C:\ProgramData\LINQPad\Updates40\448 (ymmv). This means you can't use a relative path from where the executable is, and you need to use a full URI to the files. This is why it was encoded as:

// Path to the file you want to read:
var path = "C:\Users\Your.User.Name\Documents\LINQPad Queries\Misc Files\parse_me.txt";

Since I'm keeping the same structure on my machines (so I can just copy the entire queries folder and keep working), the only difference would be the user name on the other machine. So, with this simple workaround, we can have a more generic way to access our file:

// What's the name of the file you want to work with
var file_name = "parse_me.txt";

// Let's assume you're working with the file on your desktop
var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

// This is needed to "paste" the dir and the file name (it'll add the "\" basically).
var file_location = Path.Combine(path,file_name);
    
// Now you can do:
string[] read_all_lines = System.IO.File.ReadAllLines(file_location);

(For more special folders, have a look at this MSDN page).

Now, you can obviously encode the file name as part of the path, but let's assume you want to write the output of your processing to a file, and you want it to be next to your input file. Now you can do:

// Process your file ...

// Output file name
var out_file_name = "exciting_results.txt";

// Again, combining path and file name
file_location = Path.Combine(path,file_name);

// Write your results, in this case, it's a string[]
System.IO.File.WriteAllLines(file_location, some_string_array);

// Let's let the user know we're all good
Console.Out.WriteLine( out_file_name + " saved successfully.");

Done.

Now you can work on both computers, and assuming you have the linq query (or your .NET class / project), and that your input file is in the same "relative" (directory on both machines, your code will work Smile | :) . In "relative", I mean: both "desktop" folders, or both "my document\my code" folder, etc.

Full Example

Here's a full example using Linqpad and an input / output file combo (If you're not familiar with Linqpad, the .Dump() acts a bit like you console WriteLine(), but will print objects as well).

void Main()
{
    // All this was covered above
    var file_name = "parse_me.txt";
    var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    var file_location = Path.Combine(path,file_name);
    
    // Let's read our data. In our case, it's the numbers 1-10, in words
    string[] read_all_lines = System.IO.File.ReadAllLines(file_location )
                                .Dump("This is our input")
                                ;
    
    // This list will hold all the words with an even number of chars
    var even_length = read_all_lines.Where (line =>line.Length %2 == 0 )
                        .Dump()
                        ;
                        
    // Just for fun, and so as to not repeat ourselves, let's find
    // the uneven by using the Set's Except method.
    // (read: A.Except(B) all the elements from A which are not in B)
    var uneven_lenght = read_all_lines.Except(even_length)
                        .Dump()
                        ;

    // Let's say we want only the first 2 uneven numbers
    // with more than four characters
    var first_two_uneven_longer_than_4 = uneven_lenght
            .Where ( number => number.Length > 4 )
            .Take(2)
            .Dump();
            ;
    
    // And let's save them into our output file
    System.IO.File.WriteAllLines( Path.Combine(path,"exciting_results.txt")
                                 , first_two_uneven_longer_than_4  );
}

The results will look like:

This is your user name
Your.User.Name
This is our input
5String[] (10 items)4
one
two
three
four
five
six
seven
eight
nine
ten


5IEnumerable<String> (7 items)4
one
two
three
six
seven
eight
ten

Hope you'll find it useful Smile | :)

History

  • 27 June, 2014: Initial release
  • 27 June, 2014: Update, thanks to SoMad good pointer

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

_Noctis_
Software Developer
Australia Australia
Coding since I Remember myself ... went through Basic on Commodore 64 to C# on an 8 core i7... In between worked with c, c++, java, assembler, php, pascal, JScript, SQL based DB's and a bit of NoSQL as well.
 
Love software, and I'm usually fidgeting around with technology software and hardware on my free time.
Follow on   LinkedIn

Comments and Discussions

 
QuestionCopy.com as shared folder PinmemberMember 239527730-Jun-14 9:38 
AnswerRe: Copy.com as shared folder Pinprofessional_Noctis_30-Jun-14 15:59 
QuestionDropbox Pinmemberjimpar30-Jun-14 4:00 
AnswerRe: Dropbox Pinprofessional_Noctis_30-Jun-14 15:51 
GeneralRe: Dropbox Pinmemberjimpar1-Jul-14 5:22 
QuestionThoughts PinprofessionalSoMad26-Jun-14 19:56 
AnswerRe: Thoughts Pinprofessional_Noctis_27-Jun-14 1:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.1411023.1 | Last Updated 27 Jun 2014
Article Copyright 2014 by _Noctis_
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid