get the file location when open applicaiton - c#

I created an WPF application the use a viewer for file I set the application as default application for this application (filename.myapp), now if I try to open the file it will start the application but I need to know how to get this file location and name so I can use it in the application.

If I understood your question correctly you want to know the name of the file that was double-clicked/opened with your application associated.
It is the second item in the args array of your start up event:
private void Application_Startup(object sender, StartupEventArgs e)
{
...
if(e.Args.Length > 1)
{
var filename = e.Args[1]);
}
...
}

This is how I did it in the end:
var args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
var fileName= args[1];
}

Related

C# wpf open serialized file with windows

I've a custom file. Serialization and deserialization is working
fine when using my custom functions
File > Save
File > Open
When I'm going directly in the windows explorer on my file
and want to open it with the program it's not deserializing.
How can I handle the deserialization from "outside"?
Thanks for your help.
When a file is opened from Windows Explorer with your app, the absolute path of the file is passed as the first command line argument.
In case of WPF, you can handle the Startup event of App to intercept such an argument for later opening in MainWindow.
// App.xaml.cs
public string FileToOpen;
public App()
{
Startup += (sender, e) =>
{
if (e.Args.Length > 0)
FileToOpen = e.Args[0];
};
}
// MainWindow.xaml.cs
public MainWindow()
{
var path = (Application.Current as App).FileToOpen;
if (path != null)
{
// TODO: open the file when appropriate
}
}

Save data string for the next run of wpf application

I have A function that automatically uses A printer name and prints data without opening printer Dialog.
I want to be able to keep the printer name as A resource or A file in case the printer is not exist anymore or it's name has been modified, and to keep the updated name for the next run of the application
my question is:
What is the best practice doing that?
I'm currently keep the printer name as A const string 'PRINTER_NAME'
The code :
private void print_DefaultNum_Print(object sender, EventArgs e)
{
bool isSent_ok = true;
// device-dependent string, need a FormFeed?
string s = "!U1 getvar " + "device.unique_id";
// Allow the user to select a printer.
PrintDialog pd = new PrintDialog();
pd.PrinterSettings = new PrinterSettings();
pd.PrinterSettings.PrinterName = PRINTER_NAME;
for (int i = 0; i < DEFAULT_NUM_COPIES && isSent_ok; i++)// send # of copies
{
isSent_ok = RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, deviceName);
if (isSent_ok == false)
{
if (DialogResult.OK == pd.ShowDialog(this))
{
// Send a printer-specific to the printer.
for (int j = 0; j < pd.PrinterSettings.Copies; j++)// send # of copies
RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, deviceName);
}
}
}
}
Thanks for any help!
WPF fires an event when the application is exiting. I would handle this event, and in that code, I would write any persisted data to a file. First, in App.xaml, start typing "Exit=" in your Application tag. Visual Studio should recommend adding a new event handler - click that option so it wires it up for you. Your app.xaml will look something like:
<Application x:Class="MyWpfApplication.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:MyWpfApplication.ViewModel"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ignore="http://www.galasoft.ch/ignore"
StartupUri="MainWindow.xaml"
Exit="Application_Exit"
mc:Ignorable="d ignore">
</Application>
Now go to your app.xaml.cs file and you should see an empty method called Application_Exit. Add code to save the string to a file:
private void Application_Exit(object sender, ExitEventArgs e)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, "printini.txt"); // add a file name to this path. This is your full file path.
File.WriteAllText(saveFilePath, PRINTER_NAME);
}
To load it, you can use the same process to handle the Startup event - your code for the empty method it wires up would look like this:
private void Application_Startup(object sender, StartupEventArgs e)
{
string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory); // the directory that your program is installed in
string saveFilePath = Path.Combine(applicationPath, "printini.txt"); // add a file name to this path. This is your full file path.
if (File.Exists(saveFilePath))
{
PRINTER_NAME = File.ReadAllText(saveFilePath);
}
else
{
// prompt the user for a printer...
}
}

WPF How to get second clicked file path for Single Instance App

I created my WPF single instance app by using the Microsoft.VisualBasic dll method. However I'm facing some difficulty to get the file path for second clicked file which associated with my app.
For example, I have two file "First.my" and "Second.my". When I click on file "First.my" it will launch my app and pop up message box to show "First.my" file path. Since my app is single instance app, when I click on file "Second.my" it should show the file path for "Second.my" but it still showing the file path for "First.my"..
Does anyone know how to pass the associate file path in single instance app?
Below is my code:
class WindowsFormsApp : Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
{
private App _wpfApp;
public WindowsFormsApp()
{
IsSingleInstance = true;
}
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
{
MessageBox.Show("First File");
//Get 1st click file path
GetFilePath();
_wpfApp = new App();
_wpfApp.Run();
return false;
}
protected override void OnStartupNextInstance(Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs e)
{
MessageBox.Show("Second File");
//Get 2nd click file path
GetFilePath();
}
protected void GetFilePath()
{
if (AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData != null &&
AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData.Length > 0)
{
var filePath = AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0];
var uri = new Uri(filePath);
MessageBox.Show(uri.LocalPath);
}
}
}

How to open new windows from main GUI and and pass vairable to the new window

I have an application with a Listbox with files and a menu. When I right-click an item from my listbox I have a menu for example Send. When I press 'Send' I want another window to open (I already have the new window) and in the new window I want to have the item-path that I selected (I have this path in the main window).
private void MenuItemSend_Click(object sender, RoutedEventArgs e)
{
if (listBoxFiles.SelectedIndex == -1)
{
return;
}
string filePath = (listBoxFiles.SelectedItem).ToString(); --- my file path
StatisticsWindow sForm = new StatisticsWindow();
sForm.ShowDialog(); -- open the new window
}
How can I do it ?
Thanks
Why don't you create a constructor for the window?
Instead of
new IpStatisticsWindow();
this:
new IpStatisticsWindow(filePath);
// In the IpStatisticsWindow class
public IpStatisticsWindow(string path)
{
//do something with path
}
You could of course also create a property or a method which handles it, then you can pass it there, e.g.
IPsForm.Path = filePath;
IPsForm.HandlePath(filePath);

Drag drop a file on top of .exe file to get fileinfo

As the title say.
I know how to do this in C# only, but when trying to do this with WPF I can't find out where or what to add to read the filename when the program starts.
public static void Main(string[] args)
{
if (Path.GetExtension(args[0]) == ".avi" || Path.GetExtension(args[0]) == ".mkv")
{
string pathOfFile = Path.GetFileNameWithoutExtension(args[0]);
string fullPathOfFile = Path.GetFullPath(args[0]);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(pathOfFile, fullPathOfFile));
}
else
{
MessageBox.Show("This is not a supported file, please try again..");
}
}
Found the solution. Thanks for your help :)
I'll post what I did if anyone else needs it ..
In App.xaml i added Startup="Application_Startup
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication1.App"
StartupUri="MainWindow.xaml"
Startup="Application_Startup">
<Application.Resources>
<!-- Resources scoped at the Application level should be defined here. -->
</Application.Resources>
</Application>
And in App.xaml.cs i added these lines:
public static String[] mArgs;
private void Application_Startup(object sender, StartupEventArgs e)
{
if (e.Args.Length > 0)
{
mArgs = e.Args;
}
}
Last i had to add some information in the MainWindow class.
public MainWindow()
{
this.InitializeComponent();
String[] args = App.mArgs;
}
To get the data you want, you use System.IO.Path
Watch out for the Using statement. if you only use Ex. Path.GetFileNameWithoutExtension you will get a reference error. Use System.IO.Path when getting your data.
You need to find some entry point (like OnLoad event for your main window) and then access the command line arguments like so:
string[] args = Environment.GetCommandLineArgs();
Double-click the App.xaml file in Solution Explorer. You can add the Startup event. Its e.Args property gives you access to the command line arguments.
I know the topic is old but for someone searching for something similar it might be helpful. I was trying to add this feature to my program (starting the program by dropping a file on top of the EXE) and the solution was very simple and it came from here.
My program was just messing with a couple of cells in Excel file. So it was pretty obvious that it should run and do that stuff just by dropping the excel file on it.
So I added this into the Form constructor after the component initializing and it works flawlessly for me :
public Form1()
{
InitializeComponent();
string[] args = Environment.GetCommandLineArgs();
filePathTextBox.Text = (args.Length > 1 && (Path.GetExtension(args[1]) == ".xlsx" ||
Path.GetExtension(args[1]) == ".xls")) ? args[1] : "";
}
I noticed that the first argument in args is the Path of my program, so I tested and apparently the second argument is the file path of the file I'm dropping on the exe, that's why I'm using args[1].
I would like to be corrected if I'm wrong but for now everything is working fine with my program.
You can use this for Mediaelement.
public MainWindow()
{
this.InitializeComponent();
doubleclickevent();
}
private void doubleclickevent()
{
string[] args = Environment.GetCommandLineArgs();
string[] arr = new string[]
{
".MP4",
".MKV",
".AVI"
};
foreach (string element in args)
{
foreach (string s in arr)
{
if (element.EndsWith(s))
{
MediaElement.Source = new Uri(#element, UriKind.RelativeOrAbsolute);
MediaElement.LoadedBehavior = MediaState.Play;
}
else { return; }
}
}
}
When you drag and drop files from Windows onto an EXE the EXE is launched and provided the file names as command line arguments.
public MainWindow()
{
string[] args = Environment.GetCommandLineArgs();
foreach (var s in args)
{
//do something with s (the file name)
}
}

Categories

Resources