C#拖拽文件显示文件路径

在C#中我想使文件拖拽到textbox上显示文件的路径
如我拖拽E:\Pictures\abc.jpg 到textbox上
但是我只能显示他的完整路径E:\Pictures\abc.jpg
怎么做才能只显示它所处的文件夹E:\Pictures
解决会追加悬赏
代码如下:
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Link;
else e.Effect = DragDropEffects.None;
}
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
textBox1.Text = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
}

string[] files =e.Data.GetData(DataFormats.FileDrop) as string[];
if(System.IO.Directory.Exists(files[0]))
{
//如果选择是文件夹而不是文件则跳过
MessageBox.Show("拖拽了一个文件夹");
return;
}
//显示所属的文件夹
textBox1.Text=System.IO.Path.GetDirectoryName(files[0]);

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-03-21
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
    string fullPath= ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
    string path = fullPath.Substring(0, fullPath.LastIndexOf("\\"));
    textBox1.Text = path;
}

截取下就好了

追问

但是这样的话我拖拽文件夹上去地址也会被截断啊,有没有方法只是在拖拽文件上去的时候截断?

追答private void textBox1_DragDrop(object sender, DragEventArgs e)
{
    string fullPath= ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();

    if(File.Exists(fullPath)) //如果是文件的话,则截取
    {
        string path = fullPath.Substring(0, fullPath.LastIndexOf("\\"));
        textBox1.Text = path;
    }
    else
    {
        textBox1.Text = fullPath;
    }
}

本回答被提问者采纳
第2个回答  2014-01-28
将 textBox1.Text = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
改为
string filePath= ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
textBox1.Text=filePath.SubString(0,filePah.LastIndexof('\\'));追问

但是这样的话我拖拽文件夹上去地址也会被截断啊,有没有方法只是在拖拽文件上去的时候截断?

追答

可以呀!
string filePath= ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
try
{
if( File.Exists(filePath))
{
}
textBox1.Text=filePath.SubString(0,filePah.LastIndexof('\\'));
}
catch
{
textBox1.Text=filePath;
}

第3个回答  2014-01-28
判断一下,如果字符串中包含 .jpg .txt 这样的格式,就截取,不包含就不截取。
windows下的主要文件类型就那几种。
相似回答