IE webbrowsercontrol losing .. in file path of URL - c#

When a IE browser control is embedded in a winform and the link on a page contains a relative file path the URL coming into the callback for the navigate event seems to lose "file:///../../dir/file.htm" and becomes "file:///dir/file.htm"
private void OnNavigating(object sender, WebBrowserNavigatingEventArgs e)
{
// looking at e.Url to see what happens
}
Has anyone seen similar problems? Any suggestions?

I think your URL is incorrect. If you want a relative path, just specify a relative path, such as ../../dir/file.htm. If your URL starts with a protocol specifier, then it's an absolute URL, where a .. at the start is superfluous, since you're already starting at the root of the file system.

file:///../../dir/file.htm is not a valid url. By definition the URI cannot be relative.
(Hence the 'U' in URI/URL)
I agree with other suggestions here: don't use file:///, just specify the relative path directly.

Related

Open selected file from treeview in a richtextbox

My application consists of a TreeView a RichTextBox and a Button.
The TreeView displays contents(directories, folders and files) of my system.
The Button when pressed is supposed to take the selected file from the TreeView and display it in the RichTextBox.
I have used the following code:
private void button_Click(object sender, EventArgs e)
{
string a = TreeView.SelectedNode.FullPath;
MessageBox.Show(a); //To check if it's taking the correct path
richTextBox1.LoadFile(a, RichTextBoxStreamType.PlainText);
}
The value in the string a is correct, that is TreeView.SelectedNode.FullPath returns the correct path which I confirm with the MessageBox.
However there is a runtime exception in the richTextBox1.LoadFile(a, RichTextBoxStreamType.PlainText) line.
It appends the path of the Debug folder before the actual selected file path(shown in the image), which leads to an exception.
All the files are stored locally.
How can I solve this problem?
It is because your tree nodes contains relative path to item instead of absolute.
How to prevent it? At first, you should store the full path (include drive name) in FullPath property.
If the path starts with the folder name, application tries to get the inner folder of current active folder (Debug). If the path starts with \ - app will seek the file in the root folder of current drive, if the path starts with drive name D:\ - app will seek the file on this drive. So, in your case, it will be better to pass absolute path always, it will exclude ambiguity while searching the file.
If the file should be stored relatively to the executive file, you should add some ..\ as prefix - it stands for 'going one level upper'
You can read this to get more familiar with windows pathname style.
After some research and trials I found the solution to this issue.
The reason behind this problem is that the code TreeView.SelectedNode.FullPath returns the path with an incorrect syntax.
Suppose the file you've selected in the TreeView has the path C:\Users\Admin\Desktop\test.txt
TreeView.SelectedNode.FullPath will return the path: C\Users\Admin\Desktop\test.txt which is syntactically incorrect i.e. it cannot be used directly in some other part of code.
The solution which I went for is, putting this output into a temporary string, and inserting :\\ in the 2nd place(1st index), thus making the syntax correct.(C:\\Users...)
Putting up the code I used just for reference:
private void button_Click(object sender, EventArgs e)
{
string a = TreeView.SelectedNode.FullPath.ToString();
string b = ":\\";
string c = a.Insert(1, b);
richTextBox1.LoadFile(c, RichTextBoxStreamType.PlainText);
}
Hope this helps. Thank you for the assistance I received while solving this problem.

What is the difference between an absolute and a relative path?

I am asking because I am working on a project for school. Yes this is homework. But, I'm trying to understand a little bit more, though.
This is one example of what is being asked.
• When the user clicks the “Save” button, write the selected record to the file specified in txtFilePath (absolute path not relative) without truncating the values currently inside.
This is what I have,
private void button2_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamWriter myWriter = new StreamWriter(saveFileDialog1.FileName);
myWriter.Write(txtFilePath.Text);
myWriter.Close();
}
}
Now, I don't understand if I am doing this right. I know when I save it to my desktop and I delete it from my listbox and when I try to reload it again nothing shows up. This is what I have on my form,
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader myReader = new StreamReader(openFileDialog1.FileName);
txtFilePath.Text = openFileDialog1.FileName;
txtFilePath.Text = myReader.ReadToEnd();
myReader.Close();
}
}
And this is the load,
private void Form1_Load(object sender, EventArgs e)
{
string[] myFiles = Directory.GetFiles("C:\\");
foreach (string filename in myFiles)
{
FileInfo file = new FileInfo(filename);
employeeList.Items.Add(file.Name);
}
//...
Can someone please help me make sense of this?
Say you were giving directions to a spot. You have two methods you can describe getting to the location:
Relative to where you stand,
Relative to a landmark.
Both get you to the same location, but the former doesn't always work ("take a left, then a right, go through two lights then take another right" wouldn't necessarily work from the next town over, but works from where you stand). That's essentially the difference.
If you have C:\Windows\System32, that's an absolute path. If you have Windows\System32, it will only work so long as you're starting from C:\. If you start in C:\Program Files you would need a ..\ to get there correctly.
However, no matter where you are on the hard drive, C:\Windows\System32\ is a definitive way to get to that folder.
It's actually a simple distinction. A relative file path is going to be a structure based around a root node; and an absolute path is going to be a structure based on a non ambiguous location. That sounds kind of wonky, but it's actually pretty simple.
Here are some examples:
Absolute Paths
C:\inetpub\yourapplication\default.aspx
http://www.yourapplication.com/default.aspx
These paths are absolute because they are non ambiguous. Example 1 shows an absolute file path, and example 2 shows an absolute URL.
Relative Paths
./../script/something.js
~/default.aspx
A relative path specifies a location based on some known ahead point of reference. So in example 1, you know to go up one directory, then down into a directory called script, then to a javascript file. In example two, you are specifing the aspx page contained within the root of your application.
So, germane to your specific problem, you want to write a file to a specific absolute path, which means it needs to be a non ambiguous location.
An absolute path is the whole path name required to access the location in the file system.
For example: C:\Program Files\Internet Explorer\iexplorer.exe
Where as a relative path is in relation to some landmark, usually your main executable files location or the 'start in' location set when you open the program.
For example if your main executable is in C:\Program Files\ the relative path to iexplorer.exe is Internet Explorer\iexplorer.exe.
This is done usually when you don't always know where the file will absolutely be, like which drive letter it will be installed in or which folder it will be under.
However for a good example, if your file came with your program and you know your programs installation structure, you can use relative pathing to find all your files no matter where your program is installed as opposed to abolute pathing where your program would need to be installed in the exact same location each time.

C# WebBrowser Navigate to File Path fails (file exists)

I have a web browser in C# that I want to make navigate to a path (html file) on my local pc.
I tried using this:
if (File.Exists(Path + b.HTML))
{
browserCom1.Navigate(Path + b.HTML);
}
The file Exists, but the browser is keep opening an error of Internet Explorer: "cannot find file:///(my path here)"
It is weird because the file is correct. for example if I use:
System.Windows.Forms.OpenFileDialog browseFile = new
System.Windows.Forms.OpenFileDialog();
browseFile.ShowDialog();
String path = browseFile.FileName;
browserCom1.Navigate(path);
and I select the same file that it tried navigating to before, it works.
If I print the above brwseFile File Name to Console(which is the same as my Path+b.HTML by the way), and copy-paste it into the Navigate(...) Function (changing each '\' to '//') it Doesn't work.
I have no Idea what to do.
I tried something else like:
String path=(File.Open(Path + b.HTML, FileMode.Open).Name);
browserCom1.Navigate(path);
but the application keep getting freezed upon this.
I also tried with new URI(path) and all.
How can I simpley navigate to a HTML file on my computer?
You have http slashes, but should have file system slashes, like c:\something\something.html
I had the same problem. Resolved when I cleaned for double \\ in the code.
If that's not your problem - your problem may be some else problem related to parsing from string to uri.
my path was like this: c:\users\someone1\\myFolder\protocol.htm

image control unable to display image

my code is:
string filename = FileUploader.PostedFile.FileName.Substring(fuImage.PostedFile.FileName.LastIndexOf("\\") + 1);
if(fuImage.HasFile)
{
FileUploader.SaveAs(Server.MapPath("Modules/NewUserProfile/UserPic/" + filename));
imgUser.ImageUrl = Server.MapPath("Modules/NewUserProfile/UserPic/" + filename);
}
imgUser is id of asp:Image Control.Image is uploaded in desire folder but its not display image in image control.What i am doing wrong here? Is there any postback issue.Thanks.
Use relative path for ImageUrl property.
imgUser.ImageUrl = "Modules/NewUserProfile/UserPic/" + filename;
OR use root operator ~ if Modules folder is located at root of web-app.
imgUser.ImageUrl = "~/Modules/NewUserProfile/UserPic/" + filename;
To run this code please understand the following things:
Server.MapPath() is used for getting physical Path like: D:/Img/Upload/..
so it is good idea to get path for saving image.
But in the case when you are getting the image for binding it to image control then you must have to use virtual path instead of Physical path.
Virtual path like: localhost/demo/upload/myimage.jpg.
I usually debug problems like this by first doing a view-source with your browser, and making sure the URL in the HTML source is what you expect. Then try copying the url that shows up in your view-source and pasting it into the address bar of your browser, and see if it shows up.
I think you should wait for the image to completely upload and then set the Image path to the image.
Also after rendering into the Browser use FireBug in Mozilla or Chrome Inspect Elemnt to check whether the Image has been rendered properly by looking at the image. If it broken then your image path is wrong. Try to give relative path and check.
newpic.ImageUrl = Page.ResolveURL("~/Pictures")+filename;
Server.MapPath returns physical drive location which is not useful when you are assigning to the imageurl.

Htmlfile access is denied when using Server.MapPath

I have been using Server.MapPath("page.aspx") for quite a long time, but it is just now that I faced this problem.
Basically here is my code
Session.Clear();
ShowLoggedOffControl(); //A function that setup bunch of controls visibility
OnUserLoggedOut(new EventArgs());
Response.Redirect(Server.MapPath("~/Default.aspx"));
The error would be htmlfile:access is denied at javascript execution. However when I removed Server.MapPath so that it became like this Response.Redirect("~/Default.aspx");, things work normally.
What did I do wrong? Why, how and when can I use Server.MapPath?
Thanks.
Server.MapPath maps the specified relative or virtual path to the corresponding physical directory on the server. So in your example it would end up redirecting to something like this:
c:\Projects\MyWebsite\Default.aspx
which is probably not what you want.
Response.Redirect on the other hand will resolve the '~' to the relative path root for you and resolve to something like this:
/MyVirtualDirectory/Default.aspx
As for when you would want to use Server.MapPath, you would use it if you wanted to actually find the file on the server and do something such as:
var lines = System.IO.File.ReadAllLines(Server.MapPath("~/MyTextFile.txt"));
// Do something here with values found
Server.MapPath gets the physical path to the file on the hard disk, whereas Response.Redirect expects a URL.
If for some reason you need to get the full URL, you can use this:
String.Format("http://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));

Categories