UWP Configuration file - c#

What is the best way to use a config file in a UWP application?
Store some string values in a config file that can be edited without that the application need to be rebuild everytime.
Somthing like a web.config file.

If you intend to side-load the app, you could add a text or XML file to it (with the Build Action property set to Content) that contains some pre-defined configuration values and then read from this file at runtime. e.g.:
var sampleFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("sample.txt");
var contents = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);

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 to copy a file from Visual Studio project to UWP application's LocalFolder on build

I have a Xamarin solution with a UWP project in it. I cannot understand how to copy a file that is in my VS project to the UWP LocalFolder. I've tried fiddling with the file's Build Action (Compile, Content, Embedded Resource, AdditionalFiles) and I've tried to manually create this location.
Apparently this code:
Windows.Storage.StorageFolder appDataFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
string fileName = (appDataFolder.Path + "\\HighScore.csv");
Creates this path:
'C:\Users\<my Name>\AppData\Local\Packages\ebf29fcf-0080-4b4c-b873-78fd1340811d_9tywq191txc1p\LocalState\HighScore.csv'
So I just need to figure out how to get the CSV file that's in my project to this LocalState folder. Any help appreciated.
Firstly, add the .csv file to your assets folder and set the build action to Content.
After that, you can manually copy the file from Assets to your Local Folder at runtime with the following snippet.
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/HighScore.csv"));
if (file != null)
{
// Copy .csv file to LocalFolder so we can read / write to it.
// No CollisionOption will default to Fail if file already exists,
// to copy every time the code is run, add NameCollisionOption.ReplaceExisting
await file.CopyAsync(ApplicationData.Current.LocalFolder);
// Get path of newly created file
String newFile = ApplicationData.Current.LocalFolder.Path + "/HighScore.csv";
}
You could put in some code to copy it there:
// This would point to (in respect to your build platform target):
// C:\Users\User\Source\Repos\MyAwesomeApp\MyAwesomeApp.UWP\bin\x64\Debug\AppX
Uri uri = new Uri("ms-appx:///HighScores.csv");
// throws Exception if file doesn't exist
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
// copy the file to the package:
await file.CopyAsync(ApplicationData.Current.LocalFolder);
That's the jist of it. Hope it works for you.

How to add and retrieve string values from configuration file in c#

I have a list box and that list box contain multiple string value. I want to add those strings to config file and want to read values from config and put it in list box. what should be the approach? I am new to configuration file.
The following snippet will help you modify the app.config file of your project.
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Remove("MySetting");
config.AppSettings.Settings.Add("MySetting", "some value");
config.Save(ConfigurationSaveMode.Modified);
For reading the config values, you can simply use ConfigurationManager.AppSettings["MySetting"]
You can store and retrieve configuration data for your app via it's app.config file.
You'll need to add a reference to System.Configuration in your code and add the System.Configuration assembly to your application.
Here is a good post with more info - What is App.config in C#.NET? How to use it?
probably you wanted to have those values present in a file and then read from that file and attach to your listbox like
string path = #"c:\temp\MyTest.txt";
if (File.Exists(path))
{
string[] readText = File.ReadAllLines(path);
}
You can attach that your listbox
listbox1.DataSource = new List<string>().AddRange(readText);

WriteTextAsync not writing to file

I have this piece of code:
string jsonPath = #"Model\Datamodel\UserData.json";
User userItem = JsonConvert.DeserializeObject<User>(user);
User.Add(userItem);
string content = user;
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var file = await folder.GetFileAsync(jsonPath);
await FileIO.WriteTextAsync(file,content);
Debug.WriteLine(String.Format("DONE"));
The "Done" debug line is written in console but it does not write anything to the file.
I also don't get any errors. When I debug and look at Folder and file I see that they are correctly.
Can anybody help?
You can't write to files in Windows.ApplicationModel.Package.Current.InstalledLocation, you need to use one of the other writeable locations available to you instead. (e.g. ApplicationData.Current.LocalFolder)
If you need to access the content of the file that was shipped with the package, I would suggest copying it to the local folder, and using the copy for read/write access.

Windows metro apps - write and read text files in C#?

creating text file:
var myFile = "test";
var folderUsed = Windows.Storage.ApplicationData.Current.LocalFolder;
var fileOption = Windows.Storage.CreationCollisionOption.ReplaceExisting;
var createdFile = await folderUsed.CreateFileAsync(myFile, fileOption);
writing a string into created text file:
var writeThis = "write this ";
await Windows.Storage.FileIO.WriteTextAsync(createdFile, writeThis);
However, it doesn't specify in which part the text file will be created, I'd like to create it inside the package of my app, not in somewhere else in my computer, is it possible?
And secondly, when I execute the second code again, I'd like my file to be written as "write this write this ", not replace the old file and create another one.
You should use
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
since the other folders such as installation folders are restricted and not allowed for read-write operations. Windows Store apps are pretty restricted in this area.
This link is also useful:
http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh758325.aspx
If your files are in the assets folder then you can access them by:
String path = "ms-appx:///Assets/" + Domain + ".txt";
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(path));
string Value = await FileIO.ReadTextAsync(file);
"However, it doesn't specify in which part the text file will be created, I'd like to create it inside the package of my app, not in somewhere else in my computer, is it possible?"
It's actually 'almost' the only thing possible! your application has explicit access to it's own 'LocalFolder' folder, 'RoamingFolder' location which can be shared between application instances or 'TemporaryFolder' for stuff which gets ditched.
You can save files to thing like pictures library using Windows.Storage.KnownFolders.pictureLibrary if you want, and you can get read only access to your installation folder using 'Windows.ApplicationModel.Package.current.installedLocation' if you so wish.

Categories

Resources