I am trying to load an ONNX model using WinML, with the following code:
private async Task InitializeModelAsync()
{
var path = #"ms-appx:///Assets/FER-Emotion-Recognition.onnx";
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(path));
model = await CNTKGraphModel.CreateCNTKGraphModel(file);
}
The project compiles OK, but during run-time I am getting a System.IO.FileNotFoundException:
The system cannot find the file specified.
I double checked but the file is indeed in the right folder. What did I do wrong?
Right click on your onnx file, go to the Properties panel and set its Build Action to Content.
Then, set the Copy to Output Directory to Copy if newer.
See Get started with Machine Learning
Related
public void Save_Token(string _Token)
{
var Token_Location = #".\token.txt";
using (StreamWriter sw = new StreamWriter(Token_Location))
{
sw.WriteLine(_Token);
}
}
I tried to get the token from the api (json) and I deserialized and saved it. I would like to write to the file to save for later. But I want this application to be ran on anyone's PC. So I don't want to use the full path.
I also tried
Path.Combine(Environment.CurrentDirectory,Token_Location);
still nothing is written, unless I use the full path.
You can't guarantee that the current user has write access to the folder from where the file is executed. There is a special folder (APP_DATA) that applications are supposed to use when storing user data on a computer:
public void Save_Token(string _Token)
{
var tokenDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "YourCompanyOrOrganizationName");
var tokenFile = Path.Combine(tokenDirectory, "token.txt");
Directory.CreateDirectory(tokenDirectory);
File.WriteAllText(tokenFile, _Token);
}
Your file will then be stored in a path like "C:\Users\yourusername\AppData\Roaming\YourCompanyOrOrganizationName\token.txt"
It is generally a bad idea to use a relative path in software source code because the "current working directory" of the process that the relative path is relative to can change over the runtime of the application.
Activities like showing a file open dialog or using a third-party component can unexpectedly change the current working directory so that it is dangerous to assume a certain current working directory.
firstly apology if this has already been answered and I am duplicating the question. I have tried to find the answer to my issue but have failed and none of the auto-suggestions answers my problem.
I have my main project (XAML) and also a class library project called FileStore for files. The class library project is referenced into the main project and I have images and icon file in the class library project that I can access with no issues in my main project, however, I struggle to get the content of a txt file from the CL project to display in a label on the main project. I get the error: the system could not find the file and from the error, I can see that it is trying to look for a file in the main project bin\debug folder
I tried to follow this previous post which seemed to partly answer my issue but to no avail sadly.
Get relative file path in a class library project that is being referenced by a web project
The txt file Build action is set to: Resource and Copy to Output Directory set to: Copy Always.
As I mentioned I have the FileStore project referenced in my main project and the images work fine.
Below is the code I am using, I have tried different variations such as:
\Resources\textFile.txt and \textFile.txt, still no luck.
'''
public static string ReadFileinClLibr()
{
var buildDir =
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var filePath = buildDir + #"\textFile.txt";
return File.ReadAllText(filePath);
}
'''
For comparition here is the path for the image files that works, but I cannot get it to work with the txt file, as the error reads: the given paths format is not supported..
'''
#"pack://application:,,,/FileStore;component/Resources\textFile.txt"
'''
I want to be able to input the content of the text file from the class library project to the label in the main xaml project.
At the moment compiler keeps looking for this file in a debug folder of the main project, what I want is, for the compiler to look for the txt file in a CL FileStore project
In order to access the file all the time, we have to have the file copied to the debug folder. Right click the file from solution explorer change the properties then try to access the file from the executing assembly location.
StringBuilder bodyContent = new StringBuilder();
string fileName = "myfile.txt";
try
{
string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fileName);
using (StreamReader sr = new StreamReader(filePath))
{
// Read the stream.
bodyContent.Append(sr.ReadToEnd());
}
}
catch(Exception ex)
{
Console.WriteLine(String.Format("{0} # {1}", "Exception while reading the file: " + ex.InnerException.Message, DateTime.Now));
throw ex;
}
Thanks to the post from #Sreekanth Gundlapally I have managed to fix my issues. I have mostly drawn on from the answer provided by #Sreekanth Gundlapally but there is one important bit missing. The string fileName should include any subfolders that the resource file is within in the Class Library Project, for example in my case the folder was named 'Resources' so the code should look like this:
string fileName = #"Resources/myfile.txt";
try
{
string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fileName);
using (StreamReader sr = new StreamReader(filePath))
{
// Read the stream.
bodyContent.Append(sr.ReadToEnd());
}
I have also cleaned and rebuilt solution after which it all worked a charm.
Also a side note, anyone trying this and getting funny characters make sure your file's encoding is set to UTF-8 as this is the default encoding used by StreamReader, otherwise your file content may not be read correctly if it contains signs such as apostrophe.
I want to load a PDF file in response to a Tapped event.
I added the file to my project (Add > Existing Item), set "Build Action" to "Content" and "Copy to Output Directory" to "Copy if newer"
I'm thinking the code I need may be something like this:
async Task LoadTutorial()
{
await Launcher.LaunchUriAsync(new Uri("what should be here to access the output folder?"));
}
If I'm right, what do I need to pass as the Uri? Otherwise, how is this accomplished?
UPDATE
On a related note, to add an image to the XAML using the suggested scheme, I thought this would work:
<Image Source="ms-appx:///assets/axXAndSpaceLogo.jpg"></Image>
...but it doesn't.
UPDATE 2
Trying this to open the PDF file (which is located in the root of the project, not in a subfolder):
async private void OpenTutorial()
{
IStorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
IStorageFile file = await folder.GetFileAsync("ms-appx:///PlatypusTutorial.pdf");
await Launcher.LaunchFileAsync(file);
}
...resulted in this runtime exception, thrown on the first line above:
UPDATE 3
And with this, adapted from the link provided:
var uri = new System.Uri("ms-appx:///ClayShannonResume.pdf");
var file = Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);
await Launcher.LaunchFileAsync(file);
...I get the compile time errors:
The best overloaded method match for 'Windows.System.Launcher.LaunchFileAsync(Windows.Storage.IStorageFile)' has some invalid arguments
-and:
Argument 1: cannot convert from 'Windows.Foundation.IAsyncOperation' to 'Windows.Storage.IStorageFile'
...on the last line.
UPDATE 4
According to page 76 of "Pro Windows 8 Programming" by Lecrenski, Netherlands, Sanders, and Ashely, this should work:
<Image Source="Assets/axXAndSpaceLogo.jpg" Stretch="None"></Image>
...(IOW, the "ms-appx:///" jazz is unnecessary), and it more or less does. In my particular case, with my (large) image, I had to do this:
<Image Source="Assets/axXAndSpaceLogo.jpg" Width="120" Height="80" HorizontalAlignment="Left"></Image>
Without the width and height settings, the image displayed bigger than a rhinoceros, and hugging the right side of the flyout.
UPDATE 5
I find that this works to open a PDF file ("PlatypusTut.pdf" has been added to the project, with "Build Action" set to "Content" and "Copy to Output Diretory" set to "Copy if newer"):
IStorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
IStorageFile file = await folder.GetFileAsync("PlatypusTut.pdf");
bool success = await Launcher.LaunchFileAsync(file);
if (!success)
{
MessageDialog dlgDone = new MessageDialog("Unable to open the Tutorial at this time. Try again later.");
await dlgDone.ShowAsync();
}
...but I wonder if this will only work at design-time, locally. Will this work when installed on user's machines, too? IOW, is it enough to simply pass "PlatypusTut.pdf" to GetFileAsync()?
Use the ms-appx protocol (e.g. ms-appx:///assets/image.png )to reference items in the apps package. See How to load file resources (XAML)
UPDATE:
Use GetFileFromApplicationUriAsync with ms-appx to find the file in the app package. If the file is marked as content and included in the app package then it will be available once deployed and not just from in the debugger. ms-appx:///PlatypusTut.pdf will find the PlatypusTut.pdf in the root of the app package.
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///PlatypusTut.pdf"));
await Launcher.LaunchFileAsync(file);
We did it that way:
public async Task OpenResearchAsync(string path)
{
if (path.ToLower().StartsWith("http://"))
{
await Launcher.LaunchUriAsync(new Uri(path));
}
else
{
IStorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
IStorageFile file = await folder.GetFileAsync(path);
await Launcher.LaunchFileAsync(file);
}
}
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();
....
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;