Windows Phone 7 : FileStream exception - exception

I try to use FileStream (using namespace System.IO) but I get an exception :
Attempt to access the method failed
Here is the code :
FileStream fs = new FileStream("file.txt", FileMode.Create);
I searched on microsoft.com and I found that this error is because I use a bad library reference.
But in my project, I compile with mscorlib.dll from folder : C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0
I need some help, please.

You will need to use IsolatedStorage, for example:
Place at the top of your file:
using System.IO.IsolatedStorage;
Then in your method do this:
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var istream = new IsolatedStorageFileStream("File.txt", FileMode.OpenOrCreate, store))
{
using (var sw = new StreamWriter(istream))
{
sw.Write("Some Stuff");
}
}
}
A great example and explanation of this and other operations can be found here: http://msdn.microsoft.com/en-us/library/cc265154(v=VS.95).aspx#Y300
You can look through your IsolatedStorage by using the Windows Phone 7 IsolatedStorageExplorer
A good place to start for documentation: http://msdn.microsoft.com/library/ff626516(v=VS.92).aspx
Also here: http://create.msdn.com/en-us/education/documentation

On WindowsPhone you must use IsolatedStorage - see this tutorial for example - http://3water.wordpress.com/2010/08/07/isolated-storage-on-wp7-ii/
Read:
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var readStream = new IsolatedStorageFileStream(fileName, FileMode.Open, store))
using (var reader = new StreamReader(readStream))
{
return reader.ReadToEnd();
}
Write:
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var writeStream = new IsolatedStorageFileStream(fileName, FileMode.Create, store))
using (var writer = new StreamWriter(writeStream))
{
writer.Write(content);
}

Related

FileStream - Path found in console-application but not in mvc

Iv'e used this guide drive quickstart and successfully got it worked in a console-app.
Now I'm trying to do the same thing in an mvc-application, but I got error when creating a new FileStream.
The code a use is exactly the same in mvc instead this time i'ts triggered by a button-click. This is my code:
using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 10;
listRequest.Fields = "nextPageToken, files(id, name)";
// List files.
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
.Files;
I got error at 'using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))'
My 'client_secret.json'-file is stored at the root of my mvc project.
And I've done the step: Select client_secret.json, and then go to the Properties window and set the Copy to Output Directory field to Copy always.
Why is this not working in my mvc-app?
The error I get is 'System.IO.FileNotFoundException' - '{"Cannot find file c:\windows\system32\inetsrv\client_secret.json.":"c:\windows\system32\inetsrv\client_secret.json"}'

How to encode IImageProvider as a PNG image?

Assuming I have a LumiaImagingSDK rendering chain setup, with a final IImageProvider object that I want to render, how do I encode that into a PNG image?
Lumia Imaging SDK supports PNG images as input, however there isn't a "PNG Renderer" avaliable in the SDK.
Luckily if you are developing for Windows 8.1 (StoreApplication / universal application / Windows phone 8.1 project) there is a Windows encoder (Windows.Graphics.Imaging.BitmapEncoder) you can use.
Assuming the IImageProvider you want to render is called "source" this is a code snippet you can use to encode the resulting image as PNG:
using Lumia.Imaging;
using Windows.Graphics.Imaging;
using System.IO;
...
using (var renderer = new BitmapRenderer(source, ColorMode.Bgra8888))
{
var bitmap = await renderer.RenderAsync();
byte[] pixelBuffer = bitmap.Buffers[0].Buffer.ToArray();
using (var stream = new InMemoryRandomAccessStream())
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream).AsTask().ConfigureAwait(false);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)bitmap.Dimensions.Width, (uint)bitmap.Dimensions.Height, 96, 96, pixelBuffer);
await encoder.FlushAsync().AsTask().ConfigureAwait(false);
//If InMemoryRandomAccessStream (IRandomAccessStream) works for you, end here.
//If you need an IBuffer, here is how you get one:
using (var memoryStream = new MemoryStream())
{
memoryStream.Capacity = (int)stream.Size;
var ibuffer = memoryStream.GetWindowsRuntimeBuffer();
await stream.ReadAsync(ibuffer, (uint)stream.Size, InputStreamOptions.None).AsTask().ConfigureAwait(false);
}
}
}
This will give you bytes in memory as either InMemoryRandomAccessStream (IRandomAccessStream) or an IBuffer depending on what you need. You can then save the buffer to disk or pass it to other parts of your application.

Is it possible to only read first Json Array Element from a stream with Json.net?

var serializer = new JsonSerializer();
using (var sr = new StreamReader(await blob.OpenReadAsync()))
using (var jsonTextReader = new JsonTextReader(sr))
{
var axyz = JToken.ReadFrom(jsonTextReader);
if(axyz.Type != JTokenType.Array)
{
}
}
Is there a way to just read the first element of the array with json.net. The json file is really large and i only need the first element.
You can leverage JSON#, which is designed specifically to extract embedded JSON objects from within large JSON files using something like this:
const string jsonText= #"{ "someObject": {...";
var jsonParser = new JsonObjectParser();
using (var stream =
new MemoryStream(Encoding.UTF8.GetBytes(jsonText))) {
Json.Parse(_jsonParser, stream, "myFirstObject");
}
Check out this post and the follow up tutorial series for more info.

IsolatedStorage permission error

I get a "Operation not permitted on IsolatedStorageFileStream" error when i try to run this code:
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isf.FileExists("Lokacije.abc"))
isf.CreateFile("Lokacije.abc");
using (var stream = new IsolatedStorageFileStream("Lokacije.abc", FileMode.Append, FileAccess.ReadWrite, isf))
{
using (var sw = new StreamWriter(stream))
{
sw.Write(string.Format("GC-X({0})-Y({1})|", x, y));
}
}
}
Does anyone have an idea what it could be?
I am not using the storage in any other place in my application so its impossible that it is already in use.
Check that you don't somehow have two threads accessing IsolatedStorage at the same time (ie. in VS Debug.View.Threads and verify that at the time of the exception you don't have multiple paths through the same IsoStore code).
For more refer these:
http://social.msdn.microsoft.com/Forums/wpapps/en-US/a1bb0b15-6bc0-4c63-ac94-ec1e63242cf1/operation-not-permitted-on-isolatedstoragefilestream?forum=wpdevelop
Operation not permitted on IsolatedStorageFileStream error
Hope it helps!

How can i append file using filewritersync?

I need to append file using HTML5 FileWriterSync, multiple blocks of data coming from server. I was tried to append but it was just writing a block of file only. Let's check my code.
var creator;
try {
fileEntry = fs.root.getFile(filename, {
create: creator
});
var byteArray = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
byteArray[i] = data.charCodeAt(i) & 0xff;
}
var BlobBuilderObj = new WebKitBlobBuilder();
BlobBuilderObj.append(byteArray.buffer);
if (!creator) fileEntry.createWriter().seek();
fileEntry.createWriter().write(BlobBuilderObj.getBlob())
} catch (e) {
errorHandler(e);
}
fs has been initialised before, creator changes for appending file and I need to append file.
My problem is how can I call seek to start writing from the EOF.
seek() takes an integer value for the offset. You need to set it to the file's length to do an append:
var fw = fileEntry.createWriter();
fw.seek(fw.length);
It should be similar to the async case:
http://www.html5rocks.com/en/tutorials/file/filesystem/#toc-file-appending