OpenWith Application - c#

Is there any way to detect when a file is opened with a c# application
Example
When I right-click on a file then select to open it with My Application I want this code to run
File.WriteLines(OpenWithFile)
Is this achievable

Yes, it's achievable. When a user clicks Open With in Windows Explorer, the operating system includes the filename as the first argument. Below is a demo how you'd get the file name that the user clicked to open with your application. You can than implement whatever processing you wish.
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
var OpenWithFile = args[0];
Console.WriteLine($"The OpenWithFile is: {OpenWithFile}");
}
else
{
Console.WriteLine("No command-line arguments were passed.");
}
Console.WriteLine("Press any key to continue.");
Console.ReadLine();
}
}

Related

Where to find "InOut\\" path in csharp?

I have a charp file and have created in JetBrainsRider -> Console Project.
In main method, there is code as below
static void Main(string[] args)
{
string FileNamePrefix = string.Empty;
string InfoFileName = string.Empty;
if (args.Count() > 0)
{
FileNamePrefix = args[0];
}
else
{
Console.Write("Enter File Name (no extension): ");
FileNamePrefix = Console.ReadLine();
}
InfoFileName = "InOut\\" + FileNamePrefix + "-INFO.TXT";
if (!File.Exists(InfoFileName))
{
Console.WriteLine("{0} does not exist. Run Terminated", InfoFileName);
return;
}
}
When I place a TestInput-INFO.TXT file in project folder and give name in readline input, it gives error:
Enter File Name (no extension): TestInput
InOut\TestInput-INFO.TXT does not exist. Run Terminated
Where should I put my input file?
It is relative to the current directory — see Environment.CurrentDirectory.
When executing a program from within the IDE, the exe file is located in the bin folder, and hence that is the current directory for the process.

How to open files on my desktop using C# Net.Core script?

Is there any way to make a link in C# Net Core? And whenever the user types in the user input command window to open a certain file on my PC?
Like for example:
Console.Write("Open project?: ");
string answer = Console.ReadLine();
If (answer == "yes")
{
//Open file cmd here, and one linked file for example.
}
In order to open a file or program programmatically, you firs have to know the location of that file then be sure that such file is on disk otherwise if you try to open it, it throws an error.
using System;
using System.Diagnostics;
Console.Write("Open project?: ");
string answer = Console.ReadLine();
If (answer == "yes")
{
try
{
Console.WriteLine("\nOpening file from your documents folder....");
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\myfile.txt";
Process.Start(path);
//Or a program
Process.Start("notepad.exe");
}
catch (Win32Exception ex)
{
Console.WriteLine(ex.Message);
}
}

Catching File Exceptions using c#

The below is what I am wrestling with today using Visual Studios Console App.
What I want to happen, which currently isn't, is when the Console App opens, and I type the first "checksPath" in, if this turns out to not exist, I want it to say that the path is wrong, and either, let the user try again, or close the app. If the path is valid, then it moves onto the next "reportDest", and the same applies. If it's an invalid path, I want a message saying so, with the option of trying again, or closing the app. If both paths entered (eventually) are valid, I want a message to say that the report will now produce. The rest of the script that produces the report is perfectly fine, it's just the bit i've put below that's troublesome.
string checksPath;
Console.Write("Please enter the source path for the Checks Workbook, including the name of the file (Not including the file extension): ");
checksPath = Console.ReadLine() + ".xlsx";
try
{
if (File.Exists("checksPath"))
throw new FileNotFoundException();
}
catch (FileNotFoundException e)
{
Console.WriteLine("Invalid path - Please close the app and try again!");
Console.ReadLine();
}
string reportDest;
Console.Write("Please enter the folder location and file you wish your report to go to (Not including the file extension): ");
reportDest = Console.ReadLine() + ".xlsx";
try
{
if (File.Exists("reportDest"))
throw new FileNotFoundException();
}
catch (FileNotFoundException e)
{
Console.WriteLine("Invalid path - Please close the app and try again!");
Console.ReadLine();
}
Console.WriteLine("Your report will now produce");
Since you need to continually ask a question until the user gets it right, you will need a loop. Next in that loop you need to check if the path exists.
bool run = true;
while (run)
{
Console.Clear();
Console.WriteLine("Enter Path:");
string answer = Console.ReadLine();
if (Directory.Exists(answer)) run = false;
else
{
Console.WriteLine("Path Does not exists. Try again. Press enter to continue...");
Console.ReadLine();
}
}

Trying to close an app and replace a file but I get an error on the file

static void Main(string[] args)
{
Process lsharp = Process.Start(#"C:\Users\Noo\Desktop\Documents\loader.exe");
Process myProcess = Process.Start(#"C:\Users\Noo\Desktop\Music\VoliBot.exe");
Process F5 = Process.Start(#"C:\Users\Noo\Desktop\F5.exe");
if(myProcess.HasExited == true)
{
Process[] pname = Process.GetProcessesByName("VoliBot");
if (pname.Length == 0)
F5.Kill();
File.Copy(#"C:\Users\Noo\Desktop\game.cfg", #"C:\Riot Games\League of Legends\Config\game.cfg", true);
Console.WriteLine("The Config was replaced.");
}
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}
The error is:
An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
Additional information: Access to the path 'C:\Riot Games\League of Legends\Config\game.cfg' is denied.
Some process is still keeping your file locked or you genuinely do not have access to it. You can use Process Explorer to see who has a handle on your file. In the top menu look for a subitem "Find file/handle" or something along those lines.
Also, I think you need to pass VoliBot.exe to GetProcessesByName instead of VoliBot.
And I am presuming you are Noo and not trying to access another user's home directories.

Getting an index outside bound of an array in C#

This program is supposed to show the path of a directory and the directory if its exists then it should also show the files inside with the following extensions (i.e .doc, .pdf, .jpg, .jpeg) but I'm getting an error
*Index was outside the bounds of the array.
on this line of code
string directoryPath = args[0];
This is the code in the main function
class Program
{
static void Main(string[] args)
{
string directoryPath = args[0];
string[] filesList, filesListTmp;
IFileOperation[] opList = { new FileProcNameAfter10(),
new FileProcEnc(),
new FileProcByExt("jpeg"),
new FileProcByExt("jpg"),
new FileProcByExt("doc"),
new FileProcByExt("pdf"),
new FileProcByExt("djvu")
};
if (Directory.Exists(directoryPath))
{
filesList = Directory.GetFiles(directoryPath);
while (true)
{
Thread.Sleep(500);
filesListTmp = Directory.GetFiles(directoryPath);
foreach (var elem in Enumerable.Except<string>(filesListTmp, filesList))
{
Console.WriteLine(elem);
foreach (var op in opList)
{
if (op.Accept(elem)) op.Process(elem);
}
}
filesList = filesListTmp;
if (Console.KeyAvailable == true && Console.ReadKey(true).Key == ConsoleKey.Escape) break;
}
}
else
{
Console.WriteLine("There is no such directory.");
}
}
}
How can I handle this error it seems to be common but it happens id different ways
You need to pass the necessary arguments to the program when running it. You can either do this by running the program from the command line, or else when running Visual Studio by doing the following:
Right click on project
Properties
Debug tag
Enter arguments under Start Options -> Command line arguments
You might want to pass the arguments into the program from command line.
like this:
> yourProgram.exe directoryName
Also, to avoid such problems in the code,
if(args.Length > 0){
string directoryPath = args[0];
}else{
//print a help message and exit, or do something like set the
//default directoryPath to current directory
}
Do you want the user to enter a path when the program starts or when they start the program? If it's the first, then you should add a Console.Read() method that asks for the path.
If it's the latter, then you need to pass the path as an argument when starting the program. You should also do a check against the args array before reading from it to check that it contains data and that data is a valid path.
Something like:
if(args.Length > 0 && Directory.Exists(args[0]))
{
// Do Something.
}

Categories