【问题标题】:How to get the correct and clean path while doing drag and drop in C#?如何在 C# 中进行拖放时获得正确且干净的路径?
【发布时间】:2014-07-08 16:20:22
【问题描述】:

我正在开发一个小型应用程序,它接收一个 csv 文件,删除除第二列中具有“关键”的行之外的所有行。您只需输入输入路径和输出路径,操作就完成了。一切都很好,直到我决定将其作为拖放操作。我将输入文件拖到 Windows 窗体中,文本框会自动填充我需要的路径。伟大的。然后我填充输出路径。但是,当我按下执行按钮时,出现“路径中的非法字符”错误。但是当我输入与拖动时相同的路径时,程序就可以工作了!知道他们是否是我看不到的隐藏角色吗?这是我的代码:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        this.AllowDrop = true;

    }



    private void button1_Click(object sender, EventArgs e)
    {
        String inputpath = textBox1.Text;

        String outputpath = textBox2.Text;  

        MessageBox.Show(inputpath, outputpath);





        var retainedLines = File.ReadAllLines(@inputpath)


            .Where((x, i) => i == 0 || (x.Split(',')[1]).Contains("critical")); 
        if (inputpath.Equals(outputpath))
        {
        File.Delete(@inputpath);
        }            
        File.WriteAllLines(@outputpath, retainedLines);

    }

    private void Form1_DragDrop(object sender, DragEventArgs e)
    {
        string[] fileList = (string[])e.Data.GetData(DataFormats.FileDrop, false);

        foreach (string s in fileList)
        {

            String k= String.Format("{0}{1}", s, Environment.NewLine);
            k = k.Replace("\n", String.Empty);
            textBox1.Clear();
            textBox1.Text = k;

        }




    }


    private void Form1_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
            e.Effect = DragDropEffects.All;


    }
}

【问题讨论】:

  • 我已经试过了,结果一样

标签: c# drag-and-drop


【解决方案1】:

我认为你的问题出在这两行

 String k= String.Format("{0}{1}", s, Environment.NewLine);
 k = k.Replace("\n", String.Empty);

在这里添加Environment.NewLine(Windows 操作系统定义为几个字符\r\n),然后代码删除\n,但留下\r。

因此,当您尝试读取该文件名时,您会在路径中得到一个无效字符。

一个简单的解决方法是

private void button1_Click(object sender, EventArgs e)
{
    String inputpath = textBox1.Text.Trim();
    ....
}

但您可能需要修改一下如何在 TextBox1 中添加文件。
例如,如果 Drop 操作有多个文件,您的代码将忽略,只使用列表中的最后一个文件。 (如果这是故意的,请忽略此注释)

\r 字符只是 C#(和其他 C 派生语言)中 CARRIAGE RETURN char (CR U+000D) 的转义表示

有关回车和换行字符的更多详细信息,请参阅this article on Wikipedia

【讨论】:

  • 工作就像一个魅力!非常感谢!你能告诉我有关 \r 字符的信息吗?
猜你喜欢
  • 1970-01-01
  • 2020-10-02
  • 1970-01-01
  • 1970-01-01
  • 2013-12-27
  • 1970-01-01
  • 2013-04-12
  • 2012-03-07
  • 1970-01-01
相关资源
最近更新 更多