Reputation: 103
I am trying to create a Console Application in Visual Studio using C# to be able to drag and drop a .txt file onto the .exe file and have it find and replace within that file. Eventually I also want it to then save-as with _unwrapped at the end of the original file-name. I am very new to C# and this is what I have so far. It works on the test file I have placed in the debug folder. How do I make this work with a dragged file? I tried a few things I found on google but they did not work and I did not understand them. Thank you!!
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);
}
}
}
Upvotes: 4
Views: 10343
Reputation: 13684
When you drag a file on an .exe in Windows, the .exe will be executed with the file's path as its argument. You only have to extract the argument from the args
parameter:
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);
}
Upvotes: 13