将文件拖放到控制台应用程序上

3
我正在尝试使用C#在Visual Studio中创建控制台应用程序,以便能够将.txt文件拖放到.exe文件上,并在该文件中查找和替换。最终我还希望能够将其保存为原始文件名后面加上_unwrapped的文件名。我对C#非常陌生,这是我所拥有的。它可以在我放置在调试文件夹中的测试文件上工作。如何使其与拖动的文件一起工作?我尝试了一些在谷歌上发现的方法,但它们没有起作用,而且我也不理解它们。谢谢!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = File.ReadAllText("test.txt");
            text = text.Replace("~", "~\r\n");
            File.WriteAllText("test.txt", text);

        }
    }
}

1
在谷歌上搜索“C#拖放文件到控制台应用程序”,看看你能找到什么结果。也许你应该考虑在WinForms应用程序中完成这个任务,这样你可能会更成功。 - MethodMan
1
@MethodMan 她不想把它放在窗口上,只想放在exe上。 - adjan
1个回答

12

在Windows中,当你将一个文件拖放到一个.exe文件上时,.exe文件将被执行并将该文件的路径作为其参数。你只需要从args参数中提取参数即可:

 static void Main(string[] args)
 {
    if (args.Length == 0)
       return; // return if no file was dragged onto exe
    string text = File.ReadAllText(args[0]);
    text = text.Replace("~", "~\r\n");
    string path = Path.GetDirectoryName(args[0]) 
       + Path.DirectorySeparatorChar 
       + Path.GetFileNameWithoutExtension(args[0]) 
       + "_unwrapped" + Path.GetExtension(args[0]);
    File.WriteAllText(path, text);

 }

那么这会在调试文件夹中创建一个名为test.txt的文件吗?如果是的话,对我来说不起作用。 - Emmily
@Emmily 我编辑了我的答案。现在它将拥有你想要的行为。 - adjan
你是我的英雄!非常感谢你! - Emmily

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接