//使用DialogResult来进行判断
if (DialogResult.OK == ProductOpenFileDialog.ShowDialog())
{
string filename = ProductOpenFileDialog.FileName;
filename = filename.Substring(filename.LastIndexOf("\") + 1);
txtProductImage.Text = filename;
}
if (DialogResult.OK == ProductOpenFileDialog.ShowDialog())
{
string filename = ProductOpenFileDialog.FileName;
filename = filename.Substring(filename.LastIndexOf("\") + 1);
txtProductImage.Text = filename;
}
dataAdapter.Update(dataTable);
string filename = ProductOpenFileDialog.FileName;
if (filename != null)
{
filename = filename.Substring(filename.LastIndexOf("\") + 1); //这里一直都有Newline in constant的错误,不知道怎么解决???
}
txtProductImage.Text = filename;这一段改为:
if (ProductOpenFileDialog.ShowDialog()==DialogResult.OK)
{
string filename=ProductOpenFileDialog.FileName;
filename=filename.Substring(0,filename.LastIndexOf("\\")+1);
txtProductImage.Text = filename;
}
重要的地方在两处,一是,不建议使用原文所使用的方法判断openFileDialog是否找到文件。二是要使用"\\"代替"\",楼主可重学一下C#中关于转 义字符一节。
另,filename=filename.Substring(0,filename.LastIndexOf("\\")+1); 得到的是如 C:\Ghost\的路径。而filename=filename.Substring(0,filename.LastIndexOf("\\")); 得到的是如 C:\ghost 的路径。PTW:filename=filename.Substring(filename.LastIndexOf("\\")+1);可以得到所选中文件的名称,不包括路径。
这是VB.NET的代码,功能和C#是一模一样的,但VB.NET的代码就可以运行,可C#就不行,有哪位高手能帮下忙呢?
VB.NET
Private Sub btnBrowser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowser.Click
ProductOpenFileDialog.RestoreDirectory = True
ProductOpenFileDialog.ShowDialog()
Dim filename As String = ProductOpenFileDialog.FileName()
If filename <> "" Then
filename = filename.Substring(filename.LastIndexOf("\") + 1)
End If
txtImage.Text = filename
End SubPrivate Sub txtImage_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtImage.TextChanged
If (txtImage.Text) <> "" Then
Dim img As Image
img = Image.FromFile(txtImage.Text)
picImage.Image = img
Else
picImage.Image = Nothing
End If
End Sub
上面这个是可以运行的,下个这个是有问题的!
C#
private string filename;
private Image img; private void btnBrowser_Click(object sender, System.EventArgs e)
{
FileDialog product = new OpenFileDialog();
product.InitialDirectory = "..\\";
product.Filter = "Image File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif";
product.RestoreDirectory = true ; if(product.ShowDialog() == DialogResult.OK)
{
filename = product.FileName;
filename = filename.Substring(filename.LastIndexOf("\\")+1,filename.Length -filename.LastIndexOf("\\")-1);
}
txtImage.Text = filename;
} private void txtImage_TextChanged(object sender, System.EventArgs e)
{
if (txtImage.Text != null)
{
img = Image.FromFile(filename); //就是这里出错,说读不到FILE
picImage.Image = img;
}
else
{
picImage.Image = null;
}
}
请大家帮帮我,十分感谢!
Path.GetFileName(filename)
来获得不包含路径的文件名
Path里面还有很多方法方便你取文件的信息.
http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/cpref/html/frlrfsystemiopathclassgetfilenametopic.asp