user3492682
user3492682

Reputation: 17

How to create a string for a file path in C#?

In the below code pls help me to setup a file path in asp.net ie C:\Search\City\Documents\file.txt

public string strName = "City";
public string strDocumentFolder = "Documents";
string file= "\\" + C:Search + "\\" + strName + "\\" + strDocumentFolder + "\\" + lbldoc.Text+"\\";

Upvotes: 1

Views: 755

Answers (3)

Adil
Adil

Reputation: 148110

You do not need the first \\ in start and need \\ after c: and before Search

string file=  "C:\\Search\\" + strName + "\\" + strDocumentFolder + "\\" + lbldoc.Text;

Edit

In the above we escaped the escape sequence character backslash with backslash. You can use the verbatim string to avoid the backslash interpreted as escape sequence character.

String literals

A regular string literal consists of zero or more characters enclosed in double quotes, as in "hello", and may include both simple escape sequences (such as \t for the tab character) and hexadecimal and Unicode escape sequences.

A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines.

Example

string c = "hello \t world";               // hello     world
string d = @"hello \t world";               // hello \t world

Upvotes: 2

Sunil Gudivada
Sunil Gudivada

Reputation: 184

string file = @"C:\\Search" + "\\" + strName + "\\" + strDocumentFolder + "\\" + lbldoc.Text;

Upvotes: 0

Nipun Ambastha
Nipun Ambastha

Reputation: 2573

You have 2 options

  1. Either use Server.MapPath
  2. Path.Combine

e.g.

var fullPath = Path.Combine(path, fileName);
var fullPath = Server.MapPath(fileName);

Upvotes: 1

Related Questions