Browse file and get absolute path using CefSharp - c#

I am using Cefsharp v63.0.3 NuGet package, in C# Windows Form App, I have a file upload button (HTML form input type file). I need the absolute path of the browsed file from file upload button using CefSharp. After looking some articles I found "IDialogHandler" work with file uploading but I am confused how to achieve my goal with this. Please help me out.
Form1.cs
public void InitializeChromium()
{
CefSettings settings = new CefSettings();
settings.CefCommandLineArgs.Add("enable-media-stream", "1");
Cef.Initialize(settings);
chromeBrowser = new ChromiumWebBrowser("localhost/myproject/index.html");
this.Controls.Add(chromeBrowser);
chromeBrowser.DialogHandler = new TempFileDialogHandler();
chromeBrowser.Dock = DockStyle.Fill;
}
TempFileDialogHandler.cs
public class TempFileDialogHandler : IDialogHandler
{
public bool OnFileDialog(IWebBrowser browserControl, IBrowser browser, CefFileDialogMode mode, string title, string defaultFilePath, List<string> acceptFilters, int selectedAcceptFilter, IFileDialogCallback callback)
{
//callback.Continue(selectedAcceptFilter, new List<string> { Path.GetRandomFileName() });
return true;
}
}
Thanks in advance!

Related

How can I open a .pdf file in the browser from a Xamarin UWP project?

I have a Xamarin Project where I generate a .pdf file from scratch and save it in my local storage. This works perfectly fine and can find it and open it in the disk where I saved it. However, I need to open the .pdf file immediately after creation programmatically.
I already tried different variations using Process and ProcessStartInfo but these just throw errors like "System.ComponentModel.Win32Exception: 'The system cannot find the file specified'" and "'System.PlatformNotSupportedException'".
This is basically the path I am trying to open using Process.
var p = Process.Start(#"cmd.exe", "/c start " + #"P:\\Receiving inspection\\Inspection Reports\\" + timestamp + ".pdf");
I also tried ProcessStartInfo using some variations but I'm getting the same errors all over and over.
var p = new Process();
p.StartInfo = new ProcessStartInfo(#"'P:\\Receiving inspection\\Inspection Reports\\'" + timestamp + ".pdf");
p.Start();
The better way is that use LaunchFileAsync method to open file with browser. You could create FileLauncher DependencyService to invoke uwp LaunchFileAsync method from xamarin share project.
Interface
public interface IFileLauncher
{
Task<bool> LaunchFileAsync(string uri);
}
Implementation
[assembly: Dependency(typeof(UWPFileLauncher))]
namespace App14.UWP
{
public class UWPFileLauncher : IFileLauncher
{
public async Task<bool> LaunchFileAsync(string uri)
{
var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(uri);
bool success = false;
if (file != null)
{
// Set the option to show the picker
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not
}
return success;
}
}
}
Usage
private async void Button_Clicked(object sender, EventArgs e)
{
await DependencyService.Get<IFileLauncher>().LaunchFileAsync("D:\\Key.pdf");
}
Please note if you want to access D or C disk in uwp, you need add broadFileSystemAccess capability. for more please refer this .
Update
If the UWP files are network based, not local zone based, you could use Xamarin.Essentials to open file with browser. And you must specify the privateNetworkClientServer capability in the manifest. For more please refer this link.

Webbrowser Navigate To PDF Files Does not Show Anything

I am trying to Impersonate and show the Pdf files from another computer in my network. The problem is, webbrowser goes and finds the pdf files but returns as a gray window. I guess it means that it can see the pdf but cannot load or something like that. Because when I change the path it says "The page cannot be reached". I searched about it for a couple days but couldn't find solution. I think there is no problem on impersonation because I can copy or delete or recreate the files with my program but cannot see :D Another interesting thing is when I navigate to a image file, no problem occurs. It works perfectly. Here is my code:
public class Impersonate : IDisposable
{
private static string m_UserName = "myUserName";
private static string m_Password = "mypassword";
private static string m_Domain = "myDomain";
private IntPtr token = IntPtr.Zero;
WindowsImpersonateContext person;
public void Dispose()
{
Undo();
}
public WindowsImpersonateContext Person()
{
bool success = LogonUser(m_userName, m_Domain, m_Password, 9, 0,
ref token)
if(success)
{
person = new WindowsIdentity(token).Impersonate();
return person;
}
}
public void Undo()
{
person.Undo();
Closehandle(token);
}
}
using(Impersonate imp = new Impersonate())
{
imp.Person();
string fpath = "Path_to_the_pdf_file";
newWebBrs.Navigate(new Uri(fpath));
newWebBrs.Show();
newWebbrs.Refresh();
}
The 'using' part is under a button. Any help or idea will be appreciated :D

How to Get the Name of URL Opens in IE in my application at run time

I wanted to get the name of the URL which user Opens in IE and wanted to save it to a File.I am ruuning a console application in which i wanted to get notify that new Url is open in IE and then Get that URL and save it to a File.Please Provide me some code snippet to do that .
Currently i am using this code which get the name of all URL opens but problem is that when i opens a new Url IN IE it doesnot get any new URL in my Console application.
static void Main(string[] args)
{
foreach (SHDocVw.InternetExplorer ie in new ShellWindows())
{
string filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
if (filename == "iexplore")
{
Console.WriteLine(ie.LocationURL);
StreamWriter _objStreamWriter = new StreamWriter(#"c:\file.txt", true);
_objStreamWriter.WriteLine(ie.LocationURL);
_objStreamWriter.Close();
}
}
Console.ReadKey();
}

How to load javascript in windows 8

I am looking for a way to implement Internet explorer - a desktop version in my Winodws 8 app . This is caused by my c# application- i need to run javascript page but its impossible in metro version of IE. Is there any method to do this?
I `ll describe my problem: when i want to load html of DOM page(rendered by javascript) i cant because javascript can run (I use WebView). I tried to open this page using Desktop version and it worked perfectly. Unfortunately Metro IE10 cant show the content and my WebView too.
Thanks for help.
You can sure inject in the c# webview a javascript file:
This is the action for a button:
private async void Lamp_Click(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("ms-appx:///js/injected.js");
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);
string text = await FileIO.ReadTextAsync(file); //reading content as string
var script = "(function(){" + text + "})()";
}
try
{
var result = wv.InvokeScript("eval", new string[] { script });
}
catch (Exception) { }
wv is you id name for the webview element in the xaml

Want Open a link in internal and if it contains a link,then clicking it should open in external browser in WP7

I have a browser which on Wireless connectivity opens a Uri otherwise opens a html page.
In both cases the Uri or html page opens in internal browser. Both these pages contains links.I want to open the links in external browser if user clicks them. But they always open in internal browser.
Following is my code:
private void Information_Loaded(Object sender, RoutedEventArgs e)
{
bool hasNetworkConnection =
NetworkInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211;
if (!hasNetworkConnection)
{
Assembly assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream("index_en.html"))
{
using (StreamReader reader = new StreamReader(stream))
{
string html = reader.ReadToEnd();
browser.NavigateToString(html);
}
}
}
else
{
browser.Navigate(Uri);
}
}
And xaml is :
<phone:WebBrowser Name="browser" Margin="0,78,0,0" Navigating="on_browser_navigation" />
How do I handle the click of link in the Html page or the Uri?
EDIT: I handled the Navigation event
private void on_browser_navigation(Object sender, NavigatingEventArgs e)
{
e.Cancel = true;
WebBrowserTask wbt = new WebBrowserTask();
wbt.URL = e.Uri.ToString();
wbt.Show();
}
But this does not show the required behavior in case of Uri.It directly opens the Uri in external browser.
Handle the Navigating event in the WebBrowser control.
In there check the e.Uri to see if it is an external link. If so, set e.Cancel
= true; and then use the WebBrowserTask to lauch the external link in Internet Explorer.
I was able to check to see if the URI is external or external by looking at the URI.Host:
if (!e.Uri.Host.Contains("www.mysite.com"))
{
e.Cancel = true;
}
else
{
'do something
}

Categories