How to write byte array to StorageFile in WindowsPhone 8 - windows-phone-8

I searched and found this but it's not available for Windows Phone 8 and only works for Windows Store apps:
http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.fileio.writebytesasync
How do I do this in WP8?

You can use binary writer:
byte[] buffer;
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream FS = new IsolatedStorageFileStream(fileName, FileMode.Create, ISF))
{
using (BinaryWriter BW = new BinaryWriter(FS))
{
BW.Write(buffer, 0, buffer.Lenght);
}
}
}
Or make it simpler as #KooKiz said:
using (IsolatedStorageFileStream FS = new IsolatedStorageFileStream(fileName, FileMode.Create, ISF))
{
FS.Write(buffer, 0, buffer.Lenght);
}

Related

IsolatedStorage Edit in Windows Phone ScheduledTask

I am reading data from IsolatedStorage, but can't edit it in ScheduledTask. How can I edit it?
private void StartToastTask(ScheduledTask task)
{
long rank = 0, difference = 0;
string text = "", nickname = "";
PishtiWCF.PishtiWCFServiceClient ws = ServiceClass.GetPishtiWCFSvc();
ws.GetUsersRankCompleted += (src, e) =>
{
try
{
if (e.Error == null)
{
difference = rank - e.Result.GeneralRank;
if (!String.IsNullOrEmpty(nickname))
{
if (difference < 0)
text = string.Format("{0}, {1} kişi seni geçti!", nickname, difference.ToString(), e.Result.GeneralRank);
else if (difference > 0)
text = string.Format("{0}, {1} kişiyi daha geçtin!", nickname, Math.Abs(difference).ToString(), e.Result.GeneralRank);
else if (e.Result.GeneralRank != 1)
text = string.Format("{0}, sıralamadaki yerin değişmedi!", nickname, e.Result.GeneralRank);
else
text = string.Format("{0}, en büyük sensin, böyle devam!", nickname);
}
else
return;
Mutex mut;
if (!Mutex.TryOpenExisting("IsoStorageMutex", out mut))
mut = new Mutex(false, "IsoStorageMutex");
mut.WaitOne();
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = file.OpenFile("UserRanks", FileMode.Open, FileAccess.Write))
{
StreamWriter writer = new StreamWriter(stream);
writer.Write(string.Format("{0},{1}", nickname, e.Result.GeneralRank));
writer.Close();
stream.Close();
}
}
mut.ReleaseMutex();
ShellToast toast = new ShellToast();
toast.Title = "Pishti";
toast.Content = text;
toast.Show();
}
FinishTask(task);
}
catch (Exception)
{
}
};
try
{
Mutex mut;
if (!Mutex.TryOpenExisting("IsoStorageMutex", out mut))
mut = new Mutex(false, "IsoStorageMutex");
mut.WaitOne();
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = file.OpenFile("UserRanks", FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(stream))
{
string temp = reader.ReadToEnd();
if (temp.Split(',').Count() > 1)
{
nickname = temp.Split(',')[0];
rank = long.Parse(temp.Split(',')[1]);
ws.GetUsersRankAsync(nickname);
}
reader.Close();
}
stream.Close();
}
}
mut.ReleaseMutex();
}
catch (Exception)
{
}
}
I am getting rank from UserRanks file, for example 1200, but when I get and data from WCF, edit it to 1000 and want to write it to IsolatedStorage, It doesn't crash application but it fails.
Do you know why?
Thanks.
I've fixed it with delete file.
Mutex mut;
if (!Mutex.TryOpenExisting("IsoStorageMutex", out mut))
mut = new Mutex(false, "IsoStorageMutex");
mut.WaitOne();
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
if (file.FileExists("UserRanks"))
file.DeleteFile("UserRanks");
using (IsolatedStorageFileStream stream = file.OpenFile("UserRanks", FileMode.OpenOrCreate, FileAccess.Write))
{
StreamWriter writer = new StreamWriter(stream);
writer.Write(string.Format("{0},{1}", nickname, e.Result.GeneralRank));
writer.Close();
stream.Close();
}
}
mut.ReleaseMutex();
You appear to write to the file first, which makes sense, but when you do so you use a file access mode - FileMode.Open - which means "open an existing file". The first time you do this the file won't exist and the open will fail.
You should either use FileMode.OpenOrCreate, which is self explanatory, or FileMode.Append which will open the file if it exists and seek to the end of the file, or create a new file if it doesn't.
If you want to throw away any pre-existing file (which is what your delete then create will do) then just use FileMode.Create

download Zip file from server in Windows Phone 8

I am trying to download and save Zip file from server.
I have string from server.
lastStatusCode = response.StatusCode;
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
RequestList[0].OnResponse(result, lastStatusCode);
}
if "lastStatusCode" is OK then i am making Zip file.
public async void saveFile(string response)
{
var fileBytes = System.Text.Encoding.UTF8.GetBytes(response.ToCharArray());
// Get the local folder.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
// Create a new folder name MyFolder.
var dataFolder = await local.CreateFolderAsync("TestFolder",
CreationCollisionOption.OpenIfExists);
// Create a new file named DataFile.txt.
var file = await dataFolder.CreateFileAsync("File.zip",
CreationCollisionOption.ReplaceExisting);
// Write the data from the textbox.
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(fileBytes, 0, fileBytes.Length);
}
}
what I am doing wrong? I can't open this file.
I fixed that problem! Converting Stream to String and then String to Byte was bad idea.
I was converting Stream to byte:
lock (RequestList)
{
//WebRequest request = (WebRequest)callbackResult.AsyncState;
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
Stream s = response.GetResponseStream();
lastStatusCode = response.StatusCode;
s.Position = 0;
// Now read s into a byte buffer with a little padding.
byte[] bytes = new byte[s.Length];
int numBytesToRead = (int)s.Length;
int numBytesRead = 0;
do
{
// Read may return anything from 0 to 10.
int n = s.Read(bytes, numBytesRead, numBytesToRead);
numBytesRead += n;
numBytesToRead -= n;
} while (numBytesToRead > 0);
s.Close();
WriteFile("Test.zip",bytes);
RequestList[0].OnResponse(bytes, lastStatusCode);
}
catch (WebException e)
{
Debug.WriteLine("Error : " + e.Message);
byte[] streamData = System.Text.Encoding.UTF8.GetBytes(e.Message);
RequestList[0].OnResponse(streamData, HttpStatusCode.InternalServerError);
}
}
I am making zip file here
public async void WriteFile(string fileName, byte[] response)
{
IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
IStorageFile storageFile = await applicationFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
//var content = System.Text.Encoding.UTF8.GetBytes(response);
using (Stream stream = await storageFile.OpenStreamForWriteAsync())
{
await stream.WriteAsync(response, 0, response.Length);
}
}

Zip a Local StorageFolder in windows phone 8 using SharpCompress or Sytem.IO.Compression or

I'm working on Windows phone 8 store app and need to Zip a Local StorageFolder (with some images). Environment VS 2013.
I learned that I can add references to SharpCompress & System.IO.Compression (but not .FileSystem) only.
SharpZipLib & DotNetZip don't seem to support WP8.
The examples given by SharpCompress don't work.
Any suggestion with a code will help a lot. Thanks.
System.IO.Compression:
string GuidPath = Path.Combine(LocalStorage, Guid.NewGuid().ToString()) + ".zip";
using (FileStream zipToOpen = new FileStream(GuidPath, FileMode.Create))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
{
String[] files = Directory.GetFiles(szFldrPath);
foreach( String echFile in files )
{
ZipArchiveEntry readmeEntry = archive.CreateEntry(Path.GetFileName(echFile));
using (BinaryWriter writer = new BinaryWriter(readmeEntry.Open()))
{
using (Stream source = File.OpenRead(echFile))
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
{
writer.Write(buffer, 0, bytesRead);
}
}
}
}
}
}

how to streamWrite a .zip/epub file from response to isolatedStorage if that .zip/hpub file contains .jpg, .woff (web open font format)

Actually i am trying to saving a .zip/.epub file from webResponse into my wp8 isolated storage which contains saveral .html, .png, .jpg and .woff ( Web Open Font Format) files.
my following code is saving only .html and .png files from the .zip/.epub, when it try to save .jpg and .woff format files it shows following exception.
Exception: Operation not permitted on IsolatedStorageFileStream BinaryWritter
Please help me to solve that how to streamWrite myFont.woff file ?
my code is following.
private async void ReadWebRequestCallback(IAsyncResult ar)
{
IsolatedStorageFile myIsoStorage = IsolatedStorageFile.GetUserStoreForApplication();
string dir = "/mainDir/subDir/subtosubDir";
if (!myIsoStorage.DirectoryExists(dir))
{
myIsoStorage.CreateDirectory(dir);
}
HttpWebRequest myRequest = (HttpWebRequest)ar.AsyncState;
HttpWebResponse myResponse = (HttpWebResponse)myRequest.EndGetResponse(ar);
using (StreamReader httpwebStreamReader = new StreamReader(myResponse.GetResponseStream()))
{
using (ZipInputStream s = new ZipInputStream(httpwebStreamReader.BaseStream))
{
ZipEntry theEntry;
try
{
while ((theEntry = s.GetNextEntry()) != null)
{
if (theEntry.IsDirectory)
{
string strNewDirectory = dir+"/"+theEntry.Name;
if (!myIsoStorage.DirectoryExists(strNewDirectory))
{
myIsoStorage.CreateDirectory(strNewDirectory);
}
}
else if (theEntry.IsFile)
{
string fileName = dir + "/" + theEntry.Name;
//save file to isolated storage
using (BinaryWriter streamWriter = new BinaryWriter(new IsolatedStorageFileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, myIsoStorage)))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
}
catch (Exception ze)
{
Debug.WriteLine(ze.Message);
}
}
}
}
using (IsolatedStorageFileStream fileStream = isf.OpenFile(fullFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
s.CopyTo(fileStream);
}
In my case it is the only way to save different extension's files into the isolated Storage, BinaryWriter will not work. so #KooKiz was right.
Thanks Kookiz :)

Updating xml file in windows 8 phone application

I am creating a windows 8 phone application, in which i am reading a xml file called User and add want to add the attributes id and name to the user element of the xaml using XDocument.
But I am not getting how to save it back to the xml file.
XDocument doc = XDocument.Load(#"XDocument.Load(#"Assets\User.xml");
XElement element = doc.Element("user");
XAttribute idAtt = new XAttribute("id", userDetails.UserId);
element.Add(idAtt);
XAttribute nameAtt = new XAttribute("name", userDetails.UserName);
element.Add(nameAtt);
Please help.
That's how I save my XML files:
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("User.xml", FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(PrivacyDataClass));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
{
serializer.Serialize(xmlWriter, data);
}
}
}