bdg
bdg

Reputation: 465

appending special characters to file path


I am trying to open and display the contents of a file. The file path is being created using the Windows explorer dialog box, this gets placed in a text File_Path_TB and has the format C:\Users\User\Desktop\testDoc.txt. I would like to use this file path held in File_Path_TB to open and display the contents of the document.
The desired output string is as follows @"C:\Users\User\Desktop\testDoc.txt" .
My code is as follows

private void Load_File_Contents_BTN_Click(object sender, RoutedEventArgs e)
{
      string FilePath = File_Path_TB.ToString();
      string File_Contents = File.ReadAllText(FilePath);
      MessageBox.Show(File_Contents);
}

I have tried the following;
string File_Contents = File.ReadAllText("@"" + filepath + """);

any suggestions and help would be appreciated!

Upvotes: 1

Views: 566

Answers (2)

Tony
Tony

Reputation: 17647

Use this

string FilePath = File_Path_TB.Text;

To access the Text property of the TextBox.

So you code could be:

private void Load_File_Contents_BTN_Click(object sender, RoutedEventArgs e)
{
      string FilePath = File_Path_TB.Text;
      string File_Contents = File.ReadAllText(FilePath);
      MessageBox.Show(File_Contents);
}

Upvotes: 0

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112392

This is what ReadAllText needs:

C:\Users\User\Desktop\testDoc.txt

not

@"C:\Users\User\Desktop\testDoc.txt"

The decorations @" and " belong to the C# syntax and enclose verbatim strings. They are not part of the string value but are only delimiters! filepath already contains the the right value. Don't add it anything.

string FilePath = File_Path_TB.Text;
string File_Contents = File.ReadAllText(FilePath);
...

Is all you need to do.


If you want to assign the path as string constant in C#, then you have to write

string FilePath = @"C:\Users\User\Desktop\testDoc.txt";

The contents of FilePath after this assignement is

C:\Users\User\Desktop\testDoc.txt

Upvotes: 1

Related Questions