C# webbrowser navite to local file. Spaces in path - c#

I'm using webbrowser control in C# application to display different local files, not necessarily web pages but also images and pdf.files.
I noticed that it works:
string path = "C:\MyDirectory\file.png";
webBrowser1.Navigate(path,false);
but if there are spaces in directories names it fails:
string path = "C:\My Directory\file.png";
webBrowser1.Navigate(path,false);
What is the trick to display such files correctly in webbrowser control?

Prefix your string with # for local and UNC paths.
string localpath = #"drive:\Some Folder\file with spaces.extension";
string uncPath = #"\\network machine\Resources\Some Resource.extension";

Hi sorry I can't post a comment without more rep but if I understand correctly, the WebBrowser class is basically like a IE wrapper, and so URLs with spaces or special characters in need to be encoded like so:
string path = System.Uri.EscapeDataString(url)
So that it will replace spaces with %20 etc and WebBrowser should know where to go.
Checkout the docs for EscapeDataString

Related

Is there a method to manage relative paths in C#? [duplicate]

I have xml files that contain href file paths to images (e.g. "....\images\image.jpg"). The hrefs contain relative paths. Now, I need to extract the hrefs to the images and turn them into absolute paths in the file system.
I know about the GetFullPath method, but I tried it and it only seems to work from the CurrentDirectory set, which appears to be C: so I don't see how I could use that. And still, I have the absolute path of the file containing the hrefs, and the href relative paths, so since it is a simple task for me to count back the number of "....\" parts based on the absolute path of the containing file, it seems there must be a way to do this programmatically as well.
I'm hoping there's some simple method I just don't know about! Any ideas?
string exactPath = Path.GetFullPath(yourRelativePath);
works
Assuming you know the real directory the XML file lives in use Path.Combine, e.g.
var absolute_path = Path.Combine(directoryXmlLivesIn, "..\images\image.jpg");
If you want to get back the full path with any ..'s collapsed then you can use:
Path.GetFullPath((new Uri(absolute_path)).LocalPath);
This worked.
var s = Path.Combine(#"C:\some\location", #"..\other\file.txt");
s = Path.GetFullPath(s);
It`s best way for convert the Relative path to the absolute path!
string absolutePath = System.IO.Path.GetFullPath(relativePath);
You can use Path.Combine with the "base" path, then GetFullPath on the results.
string absPathContainingHrefs = GetAbsolutePath(); // Get the "base" path
string fullPath = Path.Combine(absPathContainingHrefs, #"..\..\images\image.jpg");
fullPath = Path.GetFullPath(fullPath); // Will turn the above into a proper abs path
Have you tried Server.MapPath method. Here is an example
string relative_path = "/Content/img/Upload/Reports/59/44A0446_59-1.jpg";
string absolute_path = Server.MapPath(relative_path);
//will be c:\users\.....\Content\img\Upload\Reports\59\44A0446_59-1.jpg
This worked for me.
//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat";
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);
Take a look at Path.Combine
http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx

Link to an external file in iTextSharp

I want to provide links to files uploaded on the server in iTextSharp documents.
The problem I'm facing is the string containing my file path is getting mangled en-route from my code onto the page.
Let's say the full path for the file, I'm trying to link is "C:\site uploads\some_file.txt".
I'm trying to create the link using the "Anchor" object, like so:
string path = "C:\site uploads\some_file.txt";
string name = "some_file.txt";
Anchor anchor = new Anchor(name, new Font(Font.FontFamily.UNDEFINED, 12));
anchor.Reference = path;
pdfDoc.Add(anchor);
ASP.NET C# will double up those backslashes in "path", as it does, but iTextSharp will further alter the string to something like C%5%20site%HCuploads%20some%34file.txt, which does not work as a clickable link in my document. FYI, I know I didn't get my % codes just right; those are offered for example only.
I'm not trying to launch any external applications from my document, I just want to enable the user to download this file. Any advice would be appreciated.
Why do you link to a local file? If someone else downloads that PDF on their machine, it won't have that directory.
The backslashes and colon are escaped.
Use https:// links. If you do want to link to local files, use a file:// link.

C# file path with web browser control not working as string variable

I have a web browser control in my win form and I want to use the navigate method to open a local pdf file. If I hard code the url string as a string literal and pass that to navigate as a new Uri it works just fine:
WebBrowser wb = new WebBrowser();
...
string url = #"file:///C:\folder\01 - folder\my pdf file.pdf"
wb.Navigate(new Uri(url));
wb.Show();
As you can see, my path has spaces and it seems when I try to load the same string as a variable, (so not a string literal) the web browser doesn't know what to do. I have "shaped" my string using different methods to make it look identical to the above but since I cannot write it as a string literal it does not work. I guess the other option is to escape all backslashes but I think there is a problem with the spaces then. Can anyone give a concrete example of how to make this work by passing a string variable.
I actually managed to figure it out but I don't fully understand WHY it works. I suspect that by making the first string in the url a literal it "forces" the entire string to be treated as such (And literals work fine in the Uri method). Anyways, hopefully this helps out someone who might be stuck on the same thing.
WebBrowser wb = new WebBrowser();
string path = yourPath; // I have something like "C:\Folder 1\Folder 2"
string fileName = yourFileName; // "something.pdf"
string url = #"file:///" + path + fileName;
wb.Navigate(new Uri(url));
wb.Show();
Note: I got path by passing a openFileDialog resulting fileName to a private method that parses out the path and did the same for the fileName.

C# - Illegal characters in path

I have a database table that containing file paths of excel files that I import using a C# script.
The script works fine unless the filepath contains spaces e.g. C:\Temp\My Excel File.xls and I get an Illegal characters in path error message. Unfortunately I am not able to change the file names at the source.
If I hard code the file path to be as below it works fine.
String Filepath = #"C:\Temp\My Excel File.xls";
How do I alter this so I can include a string variable that will store the filepath from the database e.g.
String Filepath = //Code to get FilePath from database
StringCorrectedFilePath = #+FilePath;
Thanks in advance of any help
Edit: Issue is caused by files that start with a number creating invalid escape sequence. e.g. C:\Temp\20160611 My Excel File.xls
Edit 2: SOLVED - Error was caused by carriage return characters appearing after the file extension. Please see my answer for the solution.
Whether you do this
String Filepath = #"C:\Temp\My Excel File.xls";
or this
String Filepath = "C:\\Temp\\My Excel File.xls";
the string stored in memory is just C:\Temp\My Excel File.xls, whatever the debugger may tell you. So when you read some string from somewhere (database, file, user input, ...) you don't need to "escape" backslashes. So just use that string.
Path.GetInvalidFileNameChars
FilePath = string.Concat(FilePath.Split(System.IO.Path.GetInvalidFileNameChars())).Trim();
Well you can replace blank space with %20 character and while retrieving replace back with blank space again like (you may as well choose to use regular expression for the same)
String Filepath = #"C:\Temp\My Excel File.xls";
Filepath = Filepath.Replace(" ", "%20");
While retrieving back
string mypath = pathyouhavegotfromDB.Replace("%20", " ");
I think you need to put quotation marks around the path with spaces.
string filepath = #"C:\Temp\My Excel File.xls";
filepath = $"\"{filepath}\"";
Thanks for everyone's help, I tried all of these and unfortunately they didn't work which led me to believe that the issue wasn't what I originally thought.
It turns out that the files causing the Illegal characters in path all had carriage return characters at the end of the file name, after the file extension.
To resolve this I used the following code and now it works perfectly
FilePath = FilePath.TrimEnd('\r', '\n');
Thanks everyone for your help.
Try this:
String StringCorrectedFilePath = #""+ Filepath;

Access folders in root directory

Hi I am developing an asp.net web application. I have to access one of the image in images folder in root directory. I am using following code in my code behind file.
string imageDirectory = HttpContext.Current.Server.MapPath("~/images/");
string imageUrl = imageDirectory + "/img1.bmp";
This works fine in my local machine. My question is does this code work when I move my application to production ?
It should as long as you have an application root/virtual directory for your site.
Also, you can combine these two lines into:
string imageUrl = HttpContext.Current.Server.MapPath("~/images/img1.bmp");
If you're thinking of putting imageUrl into an <img> tag, then no, it won't work. Server.MapPath will return your file or directory as a local Windows file/directory name, so something like "C:\WebRoot\MyWebApplication". If you send this to the browser, obviously, the browser won't pick up the image.
What you can do is something like:
string imageUrl = ResolveClientUrl("~/images/myImage.gif");

Categories