2013-05-07 38 views
0

如何在系統路徑中使用字符串變量?下面是示例C#代碼:如何在路徑中使用字符串變量?

public class Test 
    { 
    public Item Met() 
    { 
    string file_name = "sample1.pdf"; 
    ///I' m just giving the code where I have the problem, not full code 
    /// kindly ignore the syntax errors if any 
    FileStream fileStream = File.OpenRead("c:\\Temp\\sample1.pdf"); 

     // Here I tried "C:\\Temp\\" + file_name // 

    string requestBodyStart = "\r\n\r\n--BOUNDARY\r\n" + 
        "Content-Type: application/xml\r\n" + 
        "Content-Disposition: form-data\r\n" + 
       "\r\n" + 
       envDef + "\r\n\r\n--BOUNDARY\r\n" +  
       "Content-Type: application/pdf\r\n" + 
       "Content-Disposition: file;filename=\"sample2.pdf\"; documentId=1\r\n" +   
        "\r\n"; ///Here in place of "sample.pdf" I want to use variable name 

      string requestBodyEnd = "\r\n--BOUNDARY--\r\n\r\n"; 

在我試圖"Content-Disposition: file;file_name=\" + file_name +\" 第二種情況下但我收到此:

無法識別的轉義序列,意外的字符 '\'

這是在路徑中使用變量的正確方法嗎?

謝謝。

+0

嘗試格式化你的問題的代碼。 – AgentFire 2013-05-07 06:33:26

回答

7

使用Path.Combine方法來連接兩個字符串路徑。

string file_name = "sample1.pdf"; 
FileStream fileStream = File.OpenRead(Path.Combine("c:\\Temp", file_name); 

也考慮using聲明,因爲FileStream實現IDisposable

+1

謝謝,它工作。 – 2013-05-07 06:30:07

-2

字符串中的路徑替換 '\' 與 '\\'

+1

等一下,什麼?他已經有雙斜槓。 – 2013-05-07 06:17:47

+0

'\'與'\'?有什麼不同? – 2013-05-07 06:18:35

2

你在發言中

"Content-Disposition: file;filename=\"" + file_name + "\"; documentId=1\r\n" + 

忘了兩角"秒,但我寧願String.Format

String.Format("Content-Disposition: file;filename=\"{0}\"; documentId=1\r\n", file_name) + 
+1

謝謝,已解決! – 2013-05-07 06:31:00

+0

我會試試這個。 – 2013-05-07 06:50:53

-1

更好的是你創建下載鏈接來讀取文件。

的.aspx:

<asp:Panel ID="AttachmentPanel" runat="server" Visible="false"> 
<asp:HyperLink ID="DownloadHyperLink" runat="server" Text="Download Attachment"</asp:HyperLink> 
</asp:Panel> 

的.cs:

string file_name = "http://192.168.100.1:400/sample1.pdf"; 
this.DownloadHyperLink.Attributes.Add("OnClick", "window.open('" + file_name + "')"); 
+0

-1:無法讀取。 – 2013-05-07 06:58:15

相關問題