• Welcome! The TrekBBS is the number one place to chat about Star Trek with like-minded fans.
    If you are not already a member then please register an account and join in the discussion!

Very small C# question

Lior .B.

Fleet Captain
Fleet Captain
why does the following string
private string fullPathtofile = @"c:\test.txt";

is shown as "c:\\test.txt"? should it be excatly as it written?
 
The @ ignores escape sequences in a string literal, so it sees the backslash as a backslash, and not as an escape sequence.

The variable fullPathtofile doesn't care/know how it was assigned it's value, so stores a backslash as a double backslash, so that it isn't mistaken for an escape sequence.
 
It should be valid as you have it.

Code:
class ReadFromFile
{
    static void Main()
    {
        // Read the file as one string.
        string text = System.IO.File.ReadAllText(@"c:\test.txt");

        // Display the file contents to the console.
        System.Console.WriteLine("Contents of test.txt = {0}", text);

        // Read the file lines into a string array.
        string[] lines = System.IO.File.ReadAllLines(@"c:\test2.txt");            

        System.Console.WriteLine("Contents of test2.txt =:");
        foreach (string line in lines)
        {
            Console.WriteLine("\t" + line);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
 
Thanks again :)
but hat if I would like to save the full path to a variable? I wants a const variable to use in a number of methods..
 
You can just do this:

Code:
class ReadFromFile
{
    static void Main()
    {
        string MyPathToFile = @"c:\test.txt";       

        string text = System.IO.File.ReadAllText(MyPathToFile);

        System.Console.WriteLine("Contents of file = {0}", text);

        System.Console.ReadKey();
    }
}
 
WTF is this thread about? :confused: :confused: :confused:

I thought a “C# question” had something to do with music.
 
It's a musical language. A semitone higher than the C programming language, and a semitone lower than the D programming language :p
 
If you want to store a full path in a variable, just escape every "\" by adding another "\" in front of it, e.g. "C:\\myfile.txt". That's what I normally do.
 
If you are not already a member then please register an account and join in the discussion!

Sign up / Register


Back
Top