File.cs CampusAppWP8::Utility::File CampusAppWP8::Utility //----------------------------------------------------------------------------- //<copyrightfile="File.cs"company="BTU/IIT"> //Companycopyrighttag. //</copyright> //<author>fiedlchr</author> //<sience>03.05.2013</sience> //----------------------------------------------------------------------------- namespaceCampusAppWP8.Utility { usingSystem; usingSystem.IO; usingSystem.Threading; usingSystem.Threading.Tasks; usingWindows.Storage; publicclassFile { #regionMember privatestaticreadonlyIStorageFolderLocalFolder=ApplicationData.Current.LocalFolder; privatestringfilename=string.Empty; #endregion #regionConstructor publicFile(stringfilename) { this.filename=filename; } #endregion #regionEvents publicdelegatevoidWriteCallbackFunc(); #endregion #regionMethod #regionpublic publicbyte[]ReadFile() { byte[]retValue=null; if(this.Exist()==true) { retValue=this.ReadSync(); } returnretValue; } publicvoidWriteFile(byte[]data,WriteCallbackFunconSavedCallback,WriteCallbackFunconFailedCallback) { Threadth=newThread(delegate(){this.WriteAsync(data,onSavedCallback,onFailedCallback);}); th.Start(); } publicFileInfoGetFileInfo() { FileInfoinfo=newFileInfo(File.LocalFolder.Path+"\\"+this.filename); returninfo; } publicboolExist() { returnthis.GetFileInfo().Exists; } publicasyncTask<StorageFile>AsStorageFile() { if(this.Exist()) { returnawaitFile.LocalFolder.GetFileAsync(this.filename); } returnnull; } #endregion #regionprivate privatebyte[]ReadSync() { byte[]retValue=null; using(StreamfileStream=File.LocalFolder.OpenStreamForReadAsync(this.filename).Result) { using(MemoryStreamms=newMemoryStream()) { fileStream.CopyTo(ms); retValue=ms.ToArray(); } } returnretValue; } privateasyncvoidWriteAsync(byte[]data,WriteCallbackFunconSavedCallback,WriteCallbackFunconFailedCallback) { Logger.LogMsg("writeasyncfile:"+this.filename); StorageFilefile=null; Streams=null; intcounter=0; //tryopeningthefile while((file==null)&&(counter<10)) { try { file=awaitFile.LocalFolder.CreateFileAsync(this.filename,CreationCollisionOption.ReplaceExisting); } catch(Exception) { counter++; System.Threading.Thread.Sleep(10); } } if(file==null) { if(onFailedCallback!=null) { onFailedCallback(); } return; } counter=0; //trytogetastreamonthefile while((s==null)&&(counter<10)) { try { s=awaitfile.OpenStreamForWriteAsync(); } catch(Exception) { counter++; System.Threading.Thread.Sleep(10); } } if(s==null) { if(onFailedCallback!=null) { onFailedCallback(); } return; } //writingdata try { awaits.WriteAsync(data,0,data.Length); awaits.FlushAsync(); } catch(Exceptione) { if(onFailedCallback!=null) { onFailedCallback(); } Logger.LogException(e); s.Dispose(); return; } s.Dispose(); if(onSavedCallback!=null) { onSavedCallback(); } } #endregion #endregion } }