2013-05-06 25 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(" ", "-"); 
相关问题