How can I write to a specific location in Windows Phone 8 - c#

When I press a button, I want it to overwrite a file to a specific folder.
I use this code:
private void btnArial_Click(object sender, RoutedEventArgs e)
{
string cssDocument = "body{font-family:\"Arial\";}";
//I want to write file style.css to folder css inside html
string path = Package.Current.InstalledLocation.Path + "\\Html\\css\\style.css";
if (File.Exists(path))
{
StreamWriter writer = new StreamWriter(path);
writer.Write(cssDocument);
writer.Close();
}
changeStyle(new FontFamily("Arial"));
}
When I tested on emulator and actual devide, it worked properly.
But when I submit app to store, it got error - the app exits when I press that button.

The install directory (Package.Current.InstalledLocation) is a read-only location. Unfortunately, due to the way that Visual Studio optimizes development-time deployment, it is set to read-write when the app is deployed from VS. That's why you see a difference in behavior after you submit the app to the store.
If you need to modify a file in your install directory, you must first copy it over to a writeable location - eg. your Local folder.

I prefer using Isolated storage in WP8 to write files and it never fails. Also you can use Windows.Storage apis.
private async void MyButton_Click(object sender, RoutedEventArgs e)
{
string cssDocument = "body{font-family:\"Arial\";}";
// using Windows.Storage
StorageFolder folder = ApplicationData.Current.LocalFolder;
folder = await folder.CreateFolderAsync("HTML", CreationCollisionOption.OpenIfExists);
folder = await folder.CreateFolderAsync("CSS", CreationCollisionOption.OpenIfExists);
StorageFile file = await folder.CreateFileAsync("style.css", CreationCollisionOption.ReplaceExisting);
using (var writer = new StreamWriter(await file.OpenStreamForWriteAsync()))
{
writer.Write(cssDocument);
}
// using using System.IO.IsolatedStorage;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!store.DirectoryExists("HTML/CSS"))
store.CreateDirectory("HTML/CSS");
using (var writer = new StreamWriter(store.OpenFile("HTML/CSS/style.css", FileMode.Create)))
{
writer.Write(cssDocument);
}
}
changeStyle(new FontFamily("Arial"));
}

Exactly..
Write the file in Isolated storage. Its easier and pretty straight forward. The files here can be accessed, viewed, modified, removed, replaced in a very clear way. I personally prefer the Isolated Storage.

Related

How to create a basic package to store images?

How can I create a basic package to store images, like a zip file?
All I want to do is to store 20000 images inside one package. It will be easier for my hard disk.
Also, I need to be able to enter and exit from that package, read/write , add/remove files, using C# code.
Another file format is .iso that is close to what I want, but is complicated to operate with.
I want something very basic, not complicated. Basic as a library if possible.
Is there such a thing?
If you decide to go with the virtual hard disk the steps are the following:
In Computer management right click Disk management and in the local menu click 'Create VHD'. Create a virtual hard disk with the parameters you prefer. I recommend the .vhdx and dynamically expanding flavor. After this you have a mounted, un-initialized, un formatted hard drive.
Prepare it with the necessary and usual steps. As the result you will have a hard drive with an assigned drive letter.
Use it as any hard drive you have.
After reboot it will not be automatically mounted, you have to do it manually in Disk Management or use a scheduled task to mount the drive. Here's the script for that: https://gallery.technet.microsoft.com/scriptcenter/How-to-automatically-mount-d623ce34
You can unmount it at Disk Management as well.
You can copy the file yourdiskname.vhd(x) to other computers and use it.
Thank you all for your input
It helped me decide and it direction me to this answer I find after many web search battles.
I find a practical solution, but not that efficient as I want it.
Is moving slow-ish when cycling the images from inside a zip file, because it is unpacking each of them. I must re-think the code and unzip all into a stream or some lists. I will see. For now, is working and I am very happy :)
Here is the result I came up with:
//My code so far - not very efficient but is working.
using Ionic.Zip;
using Ionic.Zlib;
string zipPath = "0Images.zip";
void CountZipFiles()
{
using (ZipFile zip = new ZipFile(zipPath))
{
totalzipFiles = zip.Count-1;
}
}
Image emptyImage = Image.FromFile("emptyFemale.jpg");
void ReadZipImage()
{
using (ZipFile zip = new ZipFile(zipPath))
{
MemoryStream tempS = new MemoryStream();
for (int i = 0; i < zip.Count; i++)
{
if (i == countMyZipImages)
{
label1.Text = zip[i].FileName;
if (zip[i].FileName.Contains(".niet"))
{
pictureBox1.Image = emptyImage;
}
else
{
zip[i].Extract(tempS);
pictureBox1.Image = Image.FromStream(tempS);
}
}
}
}
}
int totalzipFiles = 0, countMyZipImages = 0;
private void button2_Click(object sender, EventArgs e)
{
countMyZipImages--;
if (countMyZipImages < 0) countMyZipImages = totalzipFiles;
textBox1.Text = countMyZipImages.ToString();
ReadZipImage();
}
private void button3_Click(object sender, EventArgs e)
{
countMyZipImages++;
if (countMyZipImages > totalzipFiles) countMyZipImages = 0;
textBox1.Text = countMyZipImages.ToString();
ReadZipImage();
}
// and this is a HELP file for later use - hopefully will help others too. ;)
How to add Ionic.Zip.dll in c#.net project and use it:
To add a reference, right click (in Solution Explorer on your project) Reference folder and select Add Reference.
Then browse and add the file Ionic.Zip.dll
//Important to add this using's too after referencing.
using Ionic.Zip;
using Ionic.Zlib;
private void CreateZIP_Click(object sender, EventArgs e)
{
using (ZipFile zip = new ZipFile())
{
// add this map file into the "images" directory in the zip archive
zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
// add the report into a different directory named "files" in the archive
zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
zip.AddFile("ReadMe.txt");
zip.Save("MyZipFile.zip");
Exception ex = new Exception();
label1.Text = ex.Message;
}
}
//You can extract to a stream, or a fizical file !
private void button5_Click(object sender, EventArgs e)
{
using (ZipFile zip = new ZipFile("0Images.zip"))
{
MemoryStream tempS = new MemoryStream(); //stream
//{
foreach (ZipEntry ze in zip) //foreach
{
// check if you want to extract the image.name
if (ze.FileName == "00002 Riley Reid.jpg")
{
ze.Extract(tempS);
pictureBox1.Image = Image.FromStream(tempS);
}
}
//OR
for (int i = 0; i < zip.Count; i++) //for
{
if (i == countMyZipImages)
{
zip[i].Extract(tempS);
pictureBox1.Image = Image.FromStream(tempS);
}
}
//}
}
}
This is a free library I find on internet! I like it because is very little - 435kb. Here is a link I find for others if they want to use it. Dropbox - Ionic.Zip.dll[^]

How to store setting with UWP C#?

I a'm running an uwp app on Rasbperry Pi 3 with Windows 10 IoT OS via Visual Studio Remote Machine and Release is selected.
The problem is how to save settings I have made and use the same settings when run same UWP app later.
How is it done? I can read the settings from the text file from
Windows.ApplicationModel.Package.Current.InstalledLocation;
But of course I can't save any changes to the same text file.
Where exactly should I put the text file if I wan't to save changes to text file?
But perhaps I can use this
Windows.Storage.ApplicationData.Current.LocalSettings;
But how do I check if there is no value stored and put instead an default value?
With this I am trying to save these settings it doesn't work.
The point with this is that I can use these same settings when I run the same uwp app again.
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values["setting1"] = textBlockDelayValue.Text;
localSettings.Values["setting2"] = checkShow;
Where exactly should I put the text file if I wan't to save changes to
text file?
You can put the text file in Windows.Storage.ApplicationData.Current.LocalFolder of the solution and access it with this piece of code:
Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
async void WriteFile()
{
StorageFile sampleFile = await localFolder.CreateFileAsync("test.txt",
CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(sampleFile, "111");
}
async void ReadFile()
{
try
{
StorageFile sampleFile = await localFolder.GetFileAsync("test.txt");
String content = await FileIO.ReadTextAsync(sampleFile);
}
catch (Exception)
{
// Timestamp not found
}
}
But how do I check if there is no value stored and put instead an
default value?
You can read them out like this:
var value1 = ApplicationData.Current.LocalSettings.Values["setting1"];
var value2 = ApplicationData.Current.LocalSettings.Values["setting2"];

AXWindowsMediaPlayer not finding embedded resource MP3

I have a embedded resource file (MP3 to be exact) that plays a short boop. I wanted it for easy transport of the file since I have a lot more of them that I'm looking to add in.
When I try to play it, WMP just says it cannot find the file.
I'm using axWindowsMediaPlayer1.URL = #"ultraelecguitar.Properties.Resources.pitchedbeep"; to access it. It is added in the resource manager, and marked as a embedded resource. When I run my program with the file in the directory, it works just fine. When I don't, it doesn't work at all.
If you save resource as temporary file then you could provide it's path as url.
static void Main(string[] args)
{
var wmp = new WMPLib.WindowsMediaPlayer();
wmp.URL = CreateTempFileFromResource("ConsoleApplication1.mp3.somefile.mp3");
Console.ReadKey();
}
private static string CreateTempFileFromResource(string resourceName)
{
var tempFilePath = Path.GetTempFileName() + Path.GetExtension(resourceName);
using (var resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
using (var tempFileStream = new FileStream(tempFilePath, FileMode.Create))
{
resourceStream.CopyTo(tempFileStream);
}
return tempFilePath;
}

Write on a network folder from android (Xamarin) System.UnauthorizedAccessException

I created a android app to create a stockage list by capturing code bars, the idea is to write a csv file in to a network folder, because I want the app to run as much offline as it's possible.
Currently my code looks like:
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
string filename = Path.Combine(path, "stock.csv");
using (var streamWriter = new StreamWriter(filename, true))
using (var writer = new CsvWriter(streamWriter))
{
foreach (var item in articulos)
{
writer.WriteField(item.codbar);
writer.WriteField(item.reference);
writer.WriteField(item.quantity);
writer.NextRecord();
}
}
string path2 = #"\\Desktop-jce8pl5\csv\stock.csv";
File.Copy(filename, path2,true);
But I keep geting a System.UnauthorizedAccessException
I tried to enter directly to the file from another computer and there
is no problem.
I give full permission to "all" and "network"
I tried directly with IP I tried not to copy, just to create
string path = #"\\Desktop-jce8pl5\csv\stock.csv";
FileStream fs = null;
if (File.Exists(path))
{
fs = File.Open(path, FileMode.Append);
}
else
{
fs = File.Create(path);
}
But there is no way.
Any help?
Thanks.
As #RobertN sugested, I tried to connect with EX File Ex and detected that I was unable to, so I checked the windows 10 general configuration to shared folders and it was only enabled to auth users.
I changed that, then I start with the cifsmanager but on that moment we decided that, if the user has access to local network he will most sure have acces to internet, so I will send the file by email.

Clear Contents of A Text File C# (WinRT)

I am currently working on a project using the Windows Runtime and I have run into a roadblock, this was something that was always very easy to do and I feel very frustrated for not getting this right.
I have been sitting for hours and I just cannot seem to get it right. I get the "Access is denied error", also in some variations of my code when I did click on the button, nothing happened. I feel like the answer is staring me right in the face. Here is the code:
private async void btnDtlsSaveChanges(object sender, TappedRoutedEventArgs e)
{
StorageFile del = await Package.Current.InstalledLocation
.GetFileAsync("UserDetails.txt");
await del.DeleteAsync();
StorageFile file = await Package.Current.InstalledLocation.CreateFileAsync
("UserDetails.txt", CreationCollisionOption.OpenIfExists);
using (StreamWriter writer =
new StreamWriter(await file.OpenStreamForWriteAsync()))
{
await writer.WriteLineAsync("Hello World");
}
}
I also tried using ReplaceExisting instead of OpenIfExists:
StorageFile file = await Package.Current.InstalledLocation.CreateFileAsync
("UserDetails.txt", CreationCollisionOption.ReplaceExisting);
using (StreamWriter writer = new StreamWriter(await file.OpenStreamForWriteAsync()))
{
await writer.WriteLineAsync("Hello World");
}
I have tried in several ways, all leading down the same track, and I have looked at every related question on stack overflow, nothing is getting me there.
Any help would be greatly appreciated, thanks in advance.
EDIT: (Solved) Me in my stupidity and the learning of a new technology did not actually realise that there is a difference between the LocalStorage and the actual installed location, thanks to Rob Caplan for guiding me in the right direction.
You get access denied because apps don't have write access to Package.Current.InstalledLocation.
For write access you need to use your application data folders such as Windows.Storage.ApplicationData.Current.LocalFolder
If you want to ship your app with an initial data file and then update the app with user data at runtime you can copy it from InstalledLocation to LocalFolder on first run.
See App data (Windows Runtime apps) and Accessing app data with the Windows Runtime (Windows Runtime apps)
I don't know why you are using await, but the following code should be able to clear the file content for you
using (StreamWriter sw = new StreamWriter("UserDetails.txt", false))
{
sw.WriteLine("Hello world");
}
I used a button for it to test
After Clicking the button the file will be empty.
You need to use using FileMode.Create, It will create a new file or overwrite it.
private void button1_Click(object sender, EventArgs e)
{
using (FileStream NewFileStream = new FileStream(#"C:\Users\Crea\Documents\TCP.txt", FileMode.Create))
{ }
//using (StreamWriter sw = new StreamWriter(#"C:\Users\Crea\Documents\TCP.txt", true))
// {
// sw.WriteLine("Hello");
// }
}

Categories