Application.GetResourceStream can't file the file in the Uri - c#

I'm trying to access a .js file.
The file is located inside Database folder and named myfile.js which is just a JSON formatted text-file.
This is the code I'm using (this is run from MainPage.xaml.cs:
Uri uri = new Uri("/Database/myfile.js", UriKind.Relative);
var resource = Application.GetResourceStream(uri);
StreamReader streamReader = new StreamReader(resource.Stream);
string rawData = streamReader.ReadToEnd();
It always throw an exception of NullReferenceException because the resource variable is null.
So, the problem is in the Uri. I tried to use:
#"/Database/myfile.js"
"/Database/myfile.js"
"/LQI;component/Database/myfile.js"
But it doesn't work.
When I tried to move my file to root directory and replace the Uri string with
#"myfile.js"
it works! But I don't want that.
I also tried to rename the extension become .txt but nothing.
Please help.
Thanks!
Edit: I set the Build Action to "Content" which is default. I tried to set it to "Resource" but it doesn't work neither.
Edit #2: Okay, I found a clue (https://stackoverflow.com/a/12122332/2649132) that the LQI;component/Database/myfile.js only work when I set the item into Resource. And it does work.
But, the question will be still open since I doesn't work when I set the build action to "Content" with regular path.

The path is a relative path so take the leading "/" off of your path string so it reads "Database/myfile.js" and it should work fine.

Related

Local path URI in C# WPF

If I use an open file dialog box that returns the absolute value of the file this works just fine:
BMP = new BitmapImage(new Uri(filename));
However, I want to have a text file that contains the names of the files, like this:
01TopographicalMap.bmp
01ElevationCompressed.elv
01Terrain.trn
01Placenames.pns
These files are loaded sequentially. Unfortunately, the previous Uri(filename) call barfs because it wants the whole absolute path. We're already in the same folder. What do I have to do to get the Uri to just default to the folder it's already in?
Thanks, for the help.
You can use Directory.GetCurrentDirectory()
Or:
Path.Combine(Directory.GetCurrentDirectory(), filename);

How to give path to an text file in Solution using XDocument?

I want to load a xml document Swedish.xml which exists in my solution. How can i give path for that file in Xamarin.android
I am using following code:
var text = File.ReadAllText("Languages/Swedish.txt");
Console.WriteLine("text: "+text);
But i am getting Exception message:
Could not find a part of the path "//Languages/swedish.txt".
I even tried following lines:
var text = File.ReadAllText("./Languages/Swedish.txt");
var text = File.ReadAllText("./MyProject/Languages/Swedish.txt");
var text = File.ReadAllText("MyProject/Languages/Swedish.txt");
But none of them worked. Same exception message is appearing. Build Action is also set as Content. Whats wrong with the path? Thanks in advance.
Just try with this
string startupPath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName, "Languages", "Swedish.txt");
var text = File.ReadAllText(startupPath);
Try...
Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments)+"/Languages/Swedish.txt"
If you mark a file as Content Type, it will be included in the app bundle with the path that you are using within your project file. You can inspect the IPA file (it's just a renamed zip) that is created to verify that this is happening.
var text = File.ReadAllText("Languages/Swedish.txt");
should work. The file path is relative to the root of your application. You need to be sure that you are using the exact same casing in your code that the actual file uses. In the simulator the casing will not matter, but on the device the file system is case sensitive, and mismatched casing will break the app.
I've looked into this before and never found any solution to access files in this way. All roads seem to indicate building them as "content" is a dead end. You can however place them in your "Assets" folder and use them this way. To do so switch the "Content" to "AndroidAsset".
After you have done this you can now access the file within your app by calling it via
var filename = "Sweedish.txt";
string data;
using
(var sr = new StreamReader(Context.Assets.Open(code)))
data = sr.ReadToEnd();
....

Application.GetResourceStream called on a Content Resource still return null

Here is the task-related part of the VS2010 project (Windows Phone) structure:
The code is being executed from DummyMediaLibProvider.cs:
public class DummyMediaLibProvider: IMediaLibProvider
{
...
StreamResourceInfo albumArtPlaceholder =
Application.GetResourceStream(
new Uri("../Images/artwork.placeholder.png", UriKind.Relative));
artwork.placeholder.png Build Action is set to Content.
Still, whenever I run the code, Application.GetResourceStream returns null.
What may be the reason for the resource not being read to memory?
I have attempted to delete obj directory of the project, did Clean and Rebuild, but so far nothing helped.
Update:
If I apply Build Action: Resource to artwork.placeholder.png, I can get the resource stream ok though.
P.S. This is not the duplicate of Application.GetContentStream returns null for content Uri since the last had the extension (particurarly .xml) related problem.
The path supplied Application.GetResourceStream isn't relative to the position of the class, but relative to the application package.
StreamResourceInfo albumArtPlaceholder =
Application.GetResourceStream(
new Uri("Images/artwork.placeholder.png", UriKind.Relative));
Would be the correct path. You can also try with a full pack URI. (see MSDN)
And finally, Resource would be the correct Build Action for this.

Load local HTML file in a C# WebBrowser

In my app I have a WebBrowser element.
I would like to load a local file in it.
I have some questions:
Where to place the HTML file (so that it will also be installed if a user executes the setup)
how to reference the file? (e.g. my guess is the user's installation folder would not always be the same)
EDIT
I've added the HTML file to my project.
And I have set it up so that it gets copied to output folder.
When I check it it is present when run: \bin\Debug\Documentation\index.html
However when I do the following I get a 'Page cannot be displayed' error in the webbrowser element.
I use the following code to try to display the HTML file in the Webbrowser.
webBrowser1.Navigate(#".\Documentation\index.html");
Do a right click->properties on the file in Visual Studio.
Set the Copy to Output Directory to Copy always.
Then you will be able to reference your files by using a path such as #".\my_html.html"
Copy to Output Directory will put the file in the same folder as your binary dlls when the project is built. This works with any content file, even if its in a sub folder.
If you use a sub folder, that too will be copied in to the bin folder so your path would then be #".\my_subfolder\my_html.html"
In order to create a URI you can use locally (instead of served via the web), you'll need to use the file protocol, using the base directory of your binary - note: this will only work if you set the Copy to Ouptut Directory as above or the path will not be correct.
This is what you need:
string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Url = new Uri(String.Format("file:///{0}/my_html.html", curDir));
You'll have to change the variables and names of course.
quite late but it's the first hit i found from google
Instead of using the current directory or getting the assembly, just use the Application.ExecutablePath property:
//using System.IO;
string applicationDirectory = Path.GetDirectoryName(Application.ExecutablePath);
string myFile = Path.Combine(applicationDirectory, "Sample.html");
webMain.Url = new Uri("file:///" + myFile);
Note that the file:/// scheme does not work on the compact framework, at least it doesn't with 5.0.
You will need to use the following:
string appDir = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().GetName().CodeBase);
webBrowser1.Url = new Uri(Path.Combine(appDir, #"Documentation\index.html"));
Place it in the Applications setup folder or in a separte folder beneath
Reference it relative to the current directory when your app runs.
Somewhere, nearby the assembly you're going to run.
Use reflection to get path to your executing assembly, then do some magic to locate your HTML file.
Like this:
var myAssembly = System.Reflection.Assembly.GetEntryAssembly();
var myAssemblyLocation = System.IO.Path.GetDirectoryName(a.Location);
var myHtmlPath = Path.Combine(myAssemblyLocation, "my.html");
What worked for me was
<WebBrowser Source="pack://siteoforigin:,,,/StartPage.html" />
from here. I copied StartPage.html to the same output directory as the xaml-file and it loaded it from that relative path.
Windows 10 uwp application.
Try this:
webview.Navigate(new Uri("ms-appx-web:///index.html"));
Update on #ghostJago answer above
for me it worked as the following lines in VS2017
string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Navigate(new Uri(String.Format("file:///{0}/my_html.html", curDir)));
I have been trying different answers from here, but managed to derive something working, here it is:
1- Added the page in a folder i created at project level named WebPagesHelper
2- To have the page printed by webBrowser Control,
string curDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
var uri = new Uri(curDirectory);
string myFile = Path.Combine(uri.AbsolutePath, #"WebPagesHelper\index.html");
Uri new_uri = new Uri(myFile);
i had to get the assembly path, create a first uri to get an absolute path without the 'file://' attached, next i combined this absolute path with a relative path to the page in its folder, then made another URI from the result.
Then pass this to webBrowser URL property webBrowser.URL = new_uri;

How to open a WPF Content Stream?

Here's the code snippet
String str= ??????? // I want to assign c:/my/test.html to this string
Uri uri= new Uri (str);
Stream src = Application.GetContentStream(uri).Stream;
What's the correct way to do this? I'm getting "URI not relative" Exception thrown
Your problem is specific to WPF. See the Application.GetContentStream method.
You'll read that this method requires a relative URI. See "WPF Application, Resource, Content and Data files".
You have a file path - if you want to make it a URI add "file:///", ie. "file:///c:/my/test.html"
For local file URIs, you need to prefix it with:
file:///
I think you'll find your problem is that Application.GetContentStream is for a resource stream for a content data file that is located at the specified Uri. That is, deployed alongside an executable assembly.
If you look at: http://msdn.microsoft.com/en-us/library/aa970494(VS.90).aspx#Site_of_Origin_Files
You should find that the file:/// syntax as stated above is correct... But if you're going to open them you'll probably want some kind of switch to work out how to get the stream:
FileInfo fileToSave;
if (!existingFile.IsFile)
throw new ArgumentException("Input URI must represent a local file path", "existingFile");
fileToSave = new FileInfo(existingFile.LocalPath);
return fileToSave.Open(/* Args based on your needs */)
And similarly if it's a web URI:
if (!existingFile.Scheme.StartsWith("http"))
throw new ArgumentException("Input URI must represent a remote URL path", "existingFile");
// Do a WebRequest.Create call and attempt download... (Perhaps to MemoryStream for future use)
Hope that helps.
Andrew.

Categories