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

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();
....

Related

Read text file from relative path within project

I am creating a unit test which works using the following exact path:
string path = #"/Users/{username}/Coding/computershare/ChallengeSampleDataSet1.txt";
I read the text from the file by passing this path
string pricesFromFile = System.IO.File.ReadAllText(path);
However, I do not want to hardcode the complete local file path - I want to use the relative path in the project directory.
Therefore I tried the below using other articles on StackOverflow:
string path = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "ChallengeSampleDataSet1.txt");
But file is not found. How can I fix this so that I'm able to load the file when running the app from another machine?
Edit: the error in console using the second method is
System.IO.FileNotFoundException : Could not find file '/Users/{username}/Coding/computershare/bin/Debug/net5.0/ChallengeSampleDataSet1.txt'.
This should do the trick:
string path = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory + #"..\..\..\", "ChallengeSampleDataSet1.txt");
Note the direction of the slash (\)
Since the error is "/Users/{username}/Coding/computershare/bin/Debug/net5.0/ChallengeSampleDataSet1.txt" it indicates that your base directory is /bin/debug/net5.0 down from the root of the code. By double dotting up three levels, you'll be able to find the file in question.

Reading a setting file on server

I am writing a web service which currently needs to read some settings from a json file on server.
string allSettingsTxt = File.ReadAllText(settingsPath);
List<MySetting> list = JsonConvert.DeserializeObject<List<MySetting>(allSettingsTxt);
I tried giving following for the path
string settingPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"..\MyCurrentDir\setting.json");
But this path wont resolve on the actual deployment, I believe it has to be something like http://servername/settings/setting.json ??
Where can I store such json file
what path I should use to access it?
I'm not totally sure if I understand correctly what you are trying to achieve.
I assume you want to get the path of the settings file which is relative to your executable file.
This is what I do often in my own code:
var configFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "config.xml");
In this case, config.xml is expected to be in the same directory as the .EXE.
So this would be
var settingPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"..\MyCurrentDir\setting.json");
in your case.
Also see https://dailydotnettips.com/different-ways-of-getting-path/ for some explanations.

C# Accessing image inside project folder

I have a image uploader that stores my images on that project location:
C:\Users\example\source\Workspaces\project\projectsample\Content\Files
When I try to access this images with the following URL and code it breaks:
var fileURL = "~/Content/Files/image.png";
byte[] file = File.ReadAllBytes(fileURL);
Cannot find a part of the path
What I'm missing?
EDIT
Solved with the following: How to read existing text files without defining path using AXMIM solution.
You are on windows and not unix, so your fileURL is wrong. See naming files, paths, and namespaces for more info.
It should look like this:
var fileURL = #".\Content\Files\image.png";
EDIT: before its unclear, the ~ is the wrong character here, / or \ does not matter in that regard.

Application.GetResourceStream can't file the file in the Uri

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.

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;

Categories