2013-05-06 23 views
0

我寫了這段代碼用於設置文件名之前保存到我的電腦:爲什麼我只得到「的.xlsx」,而不是完整的連接字符串

string name_file = System.IO.Path.GetFileName(openFileDialog1.FileName).Split('.')[0] 
        + blYear.SelectedValue == null ? "2010" : blYear.SelectedValue 
        + ".xlsx"; 

我跟蹤代碼,並查看結果:

System.IO.Path.GetFileName(openFileDialog1.FileName).Split('.')[0] "PSIQ DIGITEL" string 
blYear.SelectedValue            null   object 
name_file               ".xlsx"   string 

我做錯了什麼?爲什麼name_file失去了原始值?同樣,在這個相同的問題中,我如何刪除最終file_name之間的空格,比如在例子「PSIQ DIGITEL」中應該是「PSIQ-DIGITEL」。

編輯

如果我刪除了這部分+ blYear.SelectedValue == null ? "2010" : blYear.SelectedValue然後將文件名拿着值精細,有什麼不對?

+0

什麼是'blYear'? – 2013-05-06 20:13:08

+0

是一個組合框組件 – Reynier 2013-05-06 20:13:54

+0

您應該使用'Path.Combine'來構建您的路徑。 'Path.Combine(part1,part2,part3,...)' – 2013-05-06 20:14:37

回答

1

使用Path類來獲取base file without extension然後將所需的部件添加到您的文件(記得要條件表達式從擴展隔離使用parenthesys)

string base_file = System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName); 
string name_file = base_file + 
        (blYear.SelectedValue == null ? "2010" : blYear.SelectedValue.ToString()) + 
        ".xlsx"; 

好吧,我認爲這樣更具可讀性。

順便說一句,用拆分,然後拿到第一個元素稱爲"test.my.file.name.csv"文件名所得數組中無法給予預期的結果

+0

非常好,這是我一直在尋找,我不知道這種方法(這是我用C#的第一步) – Reynier 2013-05-06 20:22:15

6

你的意思是這

((System.IO.Path.GetFileName(openFileDialog1.FileName).Split('.')[0] + blYear.SelectedValue) == null ? "2010" : blYear.SelectedValue) + ".xlsx" 

(System.IO.Path.GetFileName(openFileDialog1.FileName).Split('.')[0] + blYear.SelectedValue) == null ? "2010" : (blYear.SelectedValue + ".xlsx") 

System.IO.Path.GetFileName(openFileDialog1.FileName).Split('.')[0] + (blYear.SelectedValue == null ? "2010" : blYear.SelectedValue) + ".xlsx" 

或?

使用括號告訴編譯器你的意思,它不關注換行符和縮進。

0

你應該改掉你的表情分解成三個獨立的報表,並通過他們在MSVS調試跟蹤:

String nameFile; 
    nameFile = System.IO.Path.GetFileName(openFileDialog1.FileName).Split('.')[0]; 
    nameFile += blYear.SelectedValue == null ? "2010" : blYear.SelectedValue; 
    nameFile += ".xlsx"; 

...或者,更好的...

String nameFile; 
    nameFile = System.IO.Path.GetFileName(openFileDialog1.FileName); 
    nameFile = nameFile.Split('.')[0]; 
    nameFile += ((blYear.SelectedValue == null) ? "2010" : blYear.SelectedValue); 
    nameFile += ".xlsx"; 

運行一切融合在一起給人你沒有性能好處,並使疑難解答棘手。

我懷疑你會發現既不是 GetFileName(...).Split()或blYear.SelectedValue是你認爲他們應該是。

恕我直言...

1

我建議,而不是使用那一剎那GetFileNameWithoutExtension。 然後用括號將最後的「.xlsx」分隔開if

string name_file = System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName) 
       + (blYear.SelectedValue == null ? "2010" : blYear.SelectedValue) 
       + ".xlsx"; 
1

這是你的代碼做什麼:

string a = (System.IO.Path.GetFileName(openFileDialog1.FileName).Split('.')[0] 
    + blYear.SelectedValue) == null ? "2010" : blYear.SelectedValue; 
string name_file = a + ".xlsx"; 

因此,如果文件名充滿可言,你將使用所選值blYear,這可能是空的。提示:在字符串連接中使用?運算符時總是使用括號。它會讓你保持理智。

另外,使用Replace方法將空格更改爲最小值。像這樣:

name_file = name_file.Replace(" ", "-"); 
相關問題