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.
Related
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>)
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.
Directory:
App1
- MainPage.xaml.cs
- Sample.xaml
im trying to do is getting the xaml content from the sample as a string but it doesnt work since it cant find the file:
var x = Path.GetFullPath(#"sample.xaml");
FileStream s = new FileStream(x, FileMode.Open);
How can I fix this?
I haven't tried this give it a try.
Save your file in a location eg (Assets Folder)Now, make sure that the
build action is set to Content.
var storageFile = await StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appx:///Assets/youfile.xaml"));
The StorageFile you get is of course read-only, but it can be passed to any API that expects a StorageFile.
If you want to read you can try.
var result = storageFile.OpenReadAsync()
StorageFile Documentation
The source files (.xaml, .cs) are compiled, and in the deployed app they do not exist as physical files, so you can't open them this way.
I'm creating a simple app for windows 8 that writes me a xml file to documents library.
The problem is when i'm save the file, it saves it on skydrive and i want to save it on c:\Users\pc-name\Documents. I'm using KnownFolders.DocumentsLibrary and updated the manifest to save xml files too, otherwise i couldn't save any file in it.
public static async void XmlSaveFreeChallenge(Challenge currentChallenge)
{
var challenge = new XElement("Challenge");
var docSave = new XDocument(challenge);
challenge.Add(new XAttribute("Name", currentChallenge.Template));
var pontos = new XElement("Type", currentChallenge.Type);
docSave.Descendants("Challenge").FirstOrDefault().Add(pontos);
var folder = KnownFolders.DocumentsLibrary;
var outputStream = await folder.OpenStreamForWriteAsync("CaiMUfiles\\output\\Desafios\\" + currentChallenge.Template + ".xml", CreationCollisionOption.ReplaceExisting);
var ms = new MemoryStream();
docSave.Save(outputStream, SaveOptions.None);
await ms.CopyToAsync(outputStream);
}
The user gets to choose where the Documents library points. See the following option: settings charm -> Change PC Settings -> SkyDrive -> Save documents to SkyDrive by default
I'm not sure if it's possible for your app to override the user's choice there. Even if it is possible, it's probably better to respect the user's choice.
What Isaac McGarvey said is correct nevertheless there might by something that you can do. i did not found a way how to programmatically switch default saving folder for libraries but you still have access to all folders that is included in libraries. The only think is that you need to know absolute path so if you can save the path before then you can use this to get desired folder :
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync("AbsolutePath");
and then you can start enumerating creating or whatever you need. The problem is that if you use for example
List<StorageFolder> folder = await KnownFolders.DocumentsLibrary.GetFoldersAsync();
you wont get folder for Documents and folder for SkyDrive and folder for other linked folders to libraries you will just get all folders that is inside all of these folders in one list which mean you cannot choose where to save file.
I hope this helps a bit.
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.