c# - PCL.Storage, OpenAsync() not writing data -
i'm trying save file cache (in xamarin.android). when method below called, input variables contain right data. finishes without errors, when go read file, it's empty (the size correct, contains 0's).
public async task<bool> savecache(stream data, string id) { try { //cache folder in local storage ifolder rootfolder = filesystem.current.localstorage; var folder = await rootfolder.createfolderasync("cache", creationcollisionoption.openifexists); //save cached data ifile file = await folder.createfileasync(id + ".png", creationcollisionoption.replaceexisting); byte[] buffer = new byte[data.length]; data.read(buffer, 0, buffer.length); using (stream stream = await file.openasync(pclstorage.fileaccess.readandwrite)) { stream.write(buffer, 0, buffer.length); } return true; } catch { return false; } } i've read openasync() method pcl.storage library on github, method pretty easy, , expect do...
am doing wrong, or guys have suggestions on what's happening?
since stream.read() method starts reading current position of stream (see msdn), should ensure you're @ correct position before trying read anything.
in case seems data stream (that provided parameter), @ end of underlying data, calling stream.read() nothing.
to fix need seek stream start of data before you're trying read stream contents, example using stream.seek() method. fixed code example this:
public async task<bool> savecache(stream data, string id) { try { //cache folder in local storage ifolder rootfolder = filesystem.current.localstorage; var folder = await rootfolder.createfolderasync("cache", creationcollisionoption.openifexists); //save cached data ifile file = await folder.createfileasync(id + ".png", creationcollisionoption.replaceexisting); byte[] buffer = new byte[data.length]; //make sure stream @ beginning of data, read data buffer data.seek(0, seekorigin.begin); data.read(buffer, 0, buffer.length); using (stream stream = await file.openasync(pclstorage.fileaccess.readandwrite)) { stream.write(buffer, 0, buffer.length); } return true; } catch { return false; } }
Comments
Post a Comment