How to create a "data base txt" file in Windows Phone project - c#

I know that MS Windows Phone has not nice policy of forbiddings simple saving files on the phone. I want to have one file consisting data which looks like that:
//string double
A 444,0
B 332,240
...
This is database of tone corresponding to the frequency in Hz. How to built it into the app so I can read it later. I do not want to create during the run of the app but want it to be created already as a source of data for the app so I can read it.

Add the file to your project, and in the properties window for the file, set the build action to Resource.
In your code, you can retrieve a StreamResourceInfo instance by calling the Application.GetResourceStream method and then reading from it's stream using a StreamReader.
The path to the file will be "/AssemblyName;component/Folder/File.ext". Where "AssemblyName" is the name of your assembly, and "/Folder/File.ext" is the path to the file relative to your project root. For example. The following code reads the "/Data/tones.txt" file:
private void ReadTones()
{
string tonesPath = "/PhoneReadFileResource;component/Data/tones.txt";
Uri tonesUri = new Uri(tonesPath, UriKind.Relative);
StreamResourceInfo sri = Application.GetResourceStream(tonesUri);
StreamReader rdr = new StreamReader(sri.Stream);
TextDisplay.Text = rdr.ReadToEnd();
}
You can download a sample project based on your question here: http://sdrv.ms/RnVbQ3

Related

Hide Json file containing GOOGLE_APPLICATION_CREDENTIALS when building executable file in Visualstudio [SOLVED]

currently I am developing a tool that interacts with a Firebase Firestore database. When I want to make the C# Forms Application an executable file I get the .exe but also the json file which contains the Google App Credentials. However, I want to forward the tool so that you can't see the json file or read the contents of the file, so you only need the .exe file. Is there a way to achieve this? For example, define the app credentials in a C# script so that it compiles to the .exe file? If so how?
My current implementation looks like this:
string path = AppDomain.CurrentDomain.BaseDirectory + #"cloudfire.json";
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
The cloudfire.json file is directly contained in the namespace "LUX".
I also tried making the cloudfire.json file a resource, since i read this post but then the problem is, that i can't set the path of the .json, if i try it like that:
var assembly = Assembly.GetExecutingAssembly();
string resourceName = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith("cloudfire.json"));
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", resourceName);
I get the error: System.InvalidOperationException: "Sequence contains no matching element"
Is there maybe a way to set the "GOOGLE_APPLICATION_CREDENTIALS" to the embedded cloudfire.json ressource file?
EDIT:
I solved the problem by adding the "cloudfire.json" file to Resources.resx and changed the modifier to public. Like mentioned here.
Since you can only set the GOOGLE_APPLICATION_CREDENTIALS by using this code:
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "path to file");
I solved it by creating a temporary file:
byte[] resourceBytes = Properties.Resources.cloudfire;
// Write the resource to a temporary file
string tempPath = Path.GetTempFileName();
File.WriteAllBytes(tempPath, resourceBytes);
// Set the GOOGLE_APPLICATION_CREDENTIALS environment variable
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", tempPath);
Add you file as embedded resource with name. And try to read by following code:
var resources = new ResourceManager("<namespace>", Assembly.GetExecutingAssembly());
var obj = resources.GetObject(<embedded_resource_key>);
or
var str = resources.GetString(<embedded_resource_key>)

How do I get the directory for the app itself in xamarin.forms

I have a .txt file in a Resources folder that I created in the Xamarin.Forms project for the app (not the Android or iOS versions), and I want to know how to access that file as soon as the app loads. I tried just creating a StreamReader with the path "Resources/tips.txt" ("tips" is the name of the file), but that doesn't work because apparently, the current directory at that point is nothing. How do I get the directory of the app itself so I can access that folder?
Resources aren't files, you don't use file paths to access them
// MyClass is a class in the same assembly as your resource
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MyClass)).Assembly;
// see linked docs for notes about resource naming
Stream stream = assembly.GetManifestResourceStream("MyResourceName");
string text = "";
using (var reader = new System.IO.StreamReader (stream))
{
text = reader.ReadToEnd ();
}

Referencing a file inside of a Project without using its absolute path?

I'm using StreamReader to dynamically replace content in an HTML template. The HTML file has been imported into my project.
Right now I'm having to referencing the HTML file a static location on my dev box because I'm not able to find the right syntax to reference it once it's been imported into my VS project.
How do I refer to the file without using an absolute path?
Current implementation for reference:
StreamReader reader = new StreamReader(#"C:\Users\n00b\Desktop\EmailTemplate.html");
{
body = reader.ReadToEnd();
}
One common thing I've seen is to put the file's location in a configuration file. This lets you change the file location at will without having to recompile.
You can add it as an embedded resource and extract it this way.
using (Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("<namespace>.Resources.EmailTemplate.html"))
per your comment
using (System.IO.StreamReader sr = new StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("<namespace>.Resources.EmailTemplate.html"))
{
body = sr.ReadToEnd();
}
There are 2 main ways to do this, In a desktop application, the current directory of the .exe is set to the directory where it is launched from by default. Unless that is changed by launching the .exe by a shortcut with special settings, or by another process using a special feature, it should be the default value. If that is the case, you can just use a relative path. For example, if you have a file named "data.txt" in a folder called "things" inside a folder called "stuff" in the same directory as your app, you can just us the relative path "stuff/things/data.txt" directly and Windows will work it out for you.
If you need to be absolutely sure you are targeting that file, even if the app launches with a modified current directory, you can get the .exe's path, and combine it with a relative path using System.IO.Path.Combine.
var appPath = Assembly.GetEntryAssembly().Location;
var filePath = "stuff/things/data.txt"
var fullPath = System.IO.Path.Combine(appPath, filePath)
If, for some reason, you need to up "up" from the application's directory, you can use ".." to represent that parent folder of a directory. So "../data.txt" would look in the folder that contains the current directory for a file named "data.txt".
You could also change the app's current directory when it starts to be the directory of the .exe, and then reference everything via relative path, as in the first example.
var appPath = Assembly.GetEntryAssembly().Location;
System.IO.Directory.SetCurrentDirectory(appPath);
I found two solutions to this:
If you don't care if the external file is visible in the build directory/installdir of your app:
StreamReader reader = new StreamReader(#"../../EmailTemplate.html");
{
body = reader.ReadToEnd();
}
If you want your external file to be invisible once compiled:
var embeddedResource = "<namespace>.EmailTemplate.html";
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedResource))
{
StreamReader sr = new StreamReader(stream);
body = sr.ReadToEnd();
}
Note the 2nd solution requires adding your external file and changing the build action to "Embedded Resource" on the properties menu of that file within Visual Studio.

How to embed a file and then save it to a location?

I've added a test.zip to a C# project by creating a Resource1.resx and dragged to the resx tab. It is now visible in the Solution Explorer as a child of Resources.
When the program runs, I'd like to move it from the .exe to a location on the computer like My Documents.
I've a feeling I need to convert the resource to a memory stream before I can write it to file but I'm not sure how to access the file as resource or how to convert it.
I think the following extracts the resource object (then again, it doesn't error no matter what the first param is) but I'm not sure how to proceed:
var resource = new ResourceManager("test", Assembly.GetExecutingAssembly());
Since you activate the resources you have already a ResourceManager.Just use GetObject method,get the bytes of your file and write the them to a new file with File.WriteAllBytes:
var bytes = Properties.Resources.ResourceManager.GetObject("resourceName") as byte[];
File.WriteAllBytes("newFile.zip", bytes);
You should use Assembly.GetManifestResourceStream.
using (Stream x = Assembly.GetExecutingAssembly().GetManifestResourceStream("test"))
{
...
}
Reference to MSDN.

Accessing files from the project folder of a WP app

I'm new to Windows Phone development and I'm trying to do a simple training app.
I want my app to load some audio files that I've put into a folder inside the project.
Here's a short snippet:
private void LoadSound(String SoundFilePath, out SoundEffect Sound)
{
// For error checking, assume we'll fail to load the file.
Sound = null;
try
{
// Holds informations about a file stream.
StreamResourceInfo SoundFileInfo = Application.GetResourceStream(new Uri(SoundFilePath, UriKind.Relative));
My folder structure is something like
- Project
- Kits
- TestKit_128
- Bass_126.wav
and calling
Button.setSound("Kits\\TestKit_128\\bass_126.wav");
throws a System.NullReferenceException because the path is not found when the URI is created. (At least I think so!)
What should I do?
Is there any way to load files from a folder in the project or to copy them into the IsolatedStorage when I run the app for the first time?
Thanks
EDIT:
I've just opened the XAP file with WinRar and there's no "Kits" folder so I guess that my problem is how to make it add the folder to the XAP file.
I think you have to add the folder and the file to your project (i assume you are using Visual Studio). Try rightclick on your solution and add an existing object (in this case your wav file).
Did you set the build action of the wav file to "Content"? Right click on the WAV file --> properties --> build action == content.
Try this:
Uri uri = new Uri("Kits/TestKit_128/bass_126.wav", UriKind.Relative);//Above the Kits folder only the project itself.
StreamResourceInfo sr = Application.GetResourceStream(uri);
try
{
using (Stream stream = sr.Stream)
{
//working here with your data image or wav or whatever you want from URI
}
}
catch (Exception)
{
}
This is for resource inside project and working good for me. Also prevoius note about "Content" is right, it wouldn't work without it. I think the problem is double-slashes in address.

Categories

Resources