Get path+filename of file that was opened with my application - c#

I'm an amateur at c# and I've been unable to locate the answer to this.
Perhaps I am not aware of the correct terms to use.
When a video file is dragged onto my exe application, I would like the application to know that it was launched with a file and be able to know the path and filename of that file. This way, the user does not have to use the file>open menu.
Hope that makes sense.
Thanks

You can check the command line arguments which were used to launch the application.
If your application was started by dropping a file on the .exe file, there will be a single command line argument with the path of the file.
string[] args = System.Environment.GetCommandLineArgs();
if(args.Length == 1)
{
// make sure it is a file and not some other command-line argument
if(System.IO.File.Exists(args[0])
{
string filePath = args[0];
// open file etc.
}
}
As your question title states, you want the path and the file name. You can get the file name using:
System.IO.Path.GetFileName(filePath); // returns file.ext

When you drag a file into a C# application, it will goes as an command-line argument to that application. Like console applications, you can catch it on the Main method on the Program class.
I'll explain it using Windows Forms application.
Open your Program class on the solution. Your program class should look like this.
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
By default, when you create Windows Forms applications, they don't treat command line arguments. You have to make a tiny change on the signature of the Main method, so it can receive arguments:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
Now you can handle file name argument passed to the application. By default, Windows will put the file name as the first argument. Just do something like this:
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Before Application.Run method, treat the argument passed.
// I created an overload of the constructor of my Form1, so
// it can receive the File Name and load the file on some TextBox.
string fileName = null;
if (args != null && args.Length > 0)
fileName = args[0];
Application.Run(new Form1(fileName));
}
In case you want to know the constructor overload of my Form1, here it is. Hope it helps!
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Form1(string fileName) : this()
{
if (fileName == null)
return;
if (!File.Exists(fileName))
{
MessageBox.Show("Invalid file name.");
return;
}
textBox1.Text = File.ReadAllText(fileName);
}
}

You need your application's command-line arguments. When you drop a file on your application in Explorer, Explorer opens the application with the file you dropped on it. You can select as many files as you want, drop them on your application and using this line of code, files will be an array of those command line arguments.
string[] files = Environment.GetCommandLineArgs();

Related

FolderBrowserDialog won't show in a single .cs file without Form

I am trying to code a program which is executed when a file is right clicked in windows, and then a context menu feature named 'Move to' executes a file in the windows registry HKEY ClASSES. It ought to parse in "%1" as argument when it executes, so that my program knows where the file is located. However, when I compile my single .cs file, the FolderBrowserDialog won't show. I am suspecting that it is because I haven't initialized some kind of form before I call it. Is it possible in some way to choose a folder from a single c# file without including Forms?
using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
public class MoveTo : Form
{
public static string current_file_path;
public static string new_file_path;
public static string file_name;
public static void Main(string[] args){
if (args.Length > 0)
{
current_file_path = (string) args[0];
file_name = (string) current_file_path.Replace(Path.GetDirectoryName(Environment.GetCommandLineArgs()[1]), "");
var browser = new FolderBrowserDialog();
if (browser.ShowDialog()==DialogResult.OK)
{
new_file_path = browser.SelectedPath + file_name;
}else
{
Environment.Exit(1);
}
try
{
File.Move(current_file_path, new_file_path);
}catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
If you bypass the argument check and try to show the FBD in a debugger, with this exact code, you will see System.Threading.ThreadStateException: 'Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.'
As per the error message, this exception won't be raised if no debugger is attached. Put an [STAThread] attribute on your Main method, like you normally see in any windows forms app:
[STAThread]
public static void Main(string[] args)
{
...
I also recommend you add an else for your outer if, to show an error if no arguments are passed (otherwise your app will exit silently

Function is not running and creating the text file

I created the function pro:
it contains the process array
it calls another write function to make the file and write into it.
the write function writeproc:
it checks if the file at specified path is present or not.
if not it generates the file else it appends the text into the file.
when i run the code it is not doing anything.... :(
This is the main method for the console app that i have made in c#.
[STAThread]
static void Main(String[] args)
{
pro();
}
pro function:
static void pro()
{
Process[] localAll = Process.GetProcesses();
String path_pro = "C://KEYLOGS//processes.txt";
foreach(Process proc in localAll)
{
writeproc(path_pro, proc);
}
}
writeproc function:
static void writeproc(String p, Process the_process)
{
if (!File.Exists(p))
{
using (StreamWriter sw = File.CreateText(p))
{
//empty file generated.
}
}
else
{
using (StreamWriter sw = File.AppendText(p))
{
sw.WriteLine("Process: "+the_process);
}
}
}
This may be the cause of two different things.
1: The folder does not exist on your C drive so the file can't be created. (It will throw a System.IO.DirectoryNotFoundException)
Add Directory.CreateDirectory(p); to the start of your writeproc method.
2: You don't have enough rights to write to your C drive. (It will throw a System.UnauthorizedAccessException)
I suggest adding a breakpoint in your writeproc method to see what exception is being thrown.

How to get a output help integrat into a c# integrated console application

I donĀ“t get a help - Output into my cmd.
Based on my last question ( How to integrate c# help into console application ) I want integrate a help function into my c# written application.
I already integrated the help function code but i think that ist not completly.
Here my code:
namespace Application1
{
static class Program
{
// Implementation
static bool ShowHelpRequired(IEnumerable<string> args) // help function II
{
return args.Select(s => s.ToLowerInvariant())
.Intersect(new[] { "help", "/?", "--help", "-help", "-h" }).Any();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
if (ShowHelpRequired(args))
{
Console.WriteLine("Show help message here");
}
}
}
}
Could someone give me a example how to get an(help) Output into my cmd?
My Case:
Actually if i call my "GUI.exe" into the cmd with -> "GUI.exe -h", then only my "GUI.exe" will be started.
My Goal:
If i cmd and enter -> "GUI.exe -h" then the it should Comes an Output with help information about my GUI.exe
It would be great if someone could Support my to reach my Goal.
In Advance thank you very much.

Passing Arguments to another WPF Application doesn't work

i got a problem when passing two arguments from one WPF App to another WPF App.
I publish the second WPF App to my Desktop and i want to start it with my first WPF App.
First-Program:
public MainWindow()
{
InitializeComponent();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = #"C:\Users\User\Desktop\Work.application";
startInfo.Arguments = "test 1234";
Process.Start(startInfo);
}
To get the arguments in the second program i tried the following code
1.Get Arguments in Mainwindow with Environment.GetCommandLineArgs() => doesn't work
public MainWindowSecondProgram()
{
InitializeComponent();
string[] args = Environment.GetCommandLineArgs();
foreach (String element in args)
{
MessageBox.Show(element);
}
}
2.Get Arguments in App by using startup function => doesn't work
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
foreach (string element in e.Args)
{
MessageBox.Show(element);
}
}
}
Now if i copy the Work.exe (not Work.application) from my Visual Studio Project folder to my Desktop and change the path from
#"C:\Users\User\Desktop\Work.application" to
#"C:\Users\User\Desktop\Work.exe"
and run my first program again, it works perfect with
the first function and the second function.
So why is it working with the EXE but not with the published application?
Edit:
I tested both functions by passing two arguments threw the debugger and it works, but not by passing it to the published application, only EXE works.
For a Windows Store App, you need to use Application.OnLaunched. Try this code:
public partial class App : Application
{
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
MessageBox.Show(args.Arguments);
}
}
Note that you'll have to turn that string into an array yourself.
To read arguments in a ClickOnce application, use:
AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData
You can read more here.
Also, not sure, but you may need to run the ClickOnce app via the .appref-ms shortcut as opposed to the .application file itself.

Notepad (app created in c#) don't read text at start

I have a simple notepad with a rich text box. I have build the project to see if it works. I can open files with openFileDialog or save files with saveFileDialog.
The problem is :
if I set this notepad to by default program to open text files on windows, text doesn't appear in the notepad.
how can I make a function to read text when I open notepad.
UPDATE: If i set my notepad to by default text editor on the Windows i can open the notepad, and i can open or save files. The problem appear when i open a text file directly from the desktop/explorer. When i double click to the file, My Notepad is opening, but the text from the file not appear.
I am beginner at programmer, so any kind of help will be much appreciated.
I am trying to use this as constructor:
using (StreamWriter w = new StreamWriter(file))
{
w.Write(patch);
w.Close();
}
But this is not working. I know I need a function when program start, but I don't know how can I write it.
The filename you double-click on in Explorer will be passed as an args parameter to your notepad app. So you can get the file path like this:
public static void Main(string[] args){
string path = args[0];
Application.Run(new Notepad(path));
}
Here is an application that will read text from file if it is set as default file reader or if you drag-and-drop file to this app EXE.
This is console app but you should grasp a concept.
using System;
using System.IO;
namespace SampleFileOpener
{
class Program
{
static void Main(string[] args)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
if (File.Exists(arg))
{
Console.WriteLine(); //Empty line
var content = File.ReadAllText(arg);
Console.WriteLine(content);
Console.WriteLine(); //Empty line
}
}
Console.ReadLine();
}
}
}
In Form.cs (that contains designer), you can add this:
public void readOnOpen(string fileName)
{
path = fileName;
if (File.Exists(path))
{
// Write to file
textBox1.Text = File.ReadAllText(path);
}
}
In program.cs, you can add this:
[STAThread]
static void Main(string[] args)
{
//check whether you get this by double-clicking file or debug with compiler
if (args != null && args.Length > 0)
{
//if args is not NULL, it means you do it by double-clicking files
//so, you can get the filename by getting the args
string fileName = args[0];
//Check file exists
if (File.Exists(fileName))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 MainForm = new Form1();
//this would call method open (like with open dialogue)
//you can get path or filename from args in Main Form
//MainForm is your notepad form
MainForm.readOnOpen(fileName);
Application.Run(MainForm);
}
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}

Categories

Resources