File.cs CampusAppWP8::Utility::File CampusAppWP8::Utility //----------------------------------------------------------------------- //<copyrightfile="File.cs"company="BTU/IIT"> //TheMITLicense(MIT).Copyright(c)2013BTU/IIT. //</copyright> //<author>fiedlchr</author> //<date>15.10.2013</date> //<summary>Implementsthefileclass</summary> //----------------------------------------------------------------------- namespaceCampusAppWP8.Utility { usingSystem; usingSystem.IO; usingSystem.Threading; usingSystem.Threading.Tasks; usingCampusAppWPortalLib8.Utility; usingWindows.Storage; publicclassFile:AbstractFile { #regionMember privatestaticreadonlyIStorageFolderLocalFolder=ApplicationData.Current.LocalFolder; privatestringfilename=string.Empty; #endregion #regionConstructor publicFile(stringfilename) { this.filename=filename; } #endregion #regionMethod #regionpublic publicoverridebyte[]ReadFile() { byte[]retValue=null; if(this.Exist()==true) { retValue=this.ReadSync(); } returnretValue; } publicoverridevoidWriteFile(byte[]data,WriteCallbackFunconSavedCallback,WriteCallbackFunconFailedCallback) { Threadth=newThread(delegate(){this.WriteAsync(data,onSavedCallback,onFailedCallback);}); th.Start(); } publicFileInfoGetFileInfo() { FileInfoinfo=newFileInfo(File.LocalFolder.Path+"\\"+this.filename); returninfo; } publicoverrideboolExist() { FileInfoinfo=this.GetFileInfo(); if(info.Exists&&info.Length>0) { returntrue; } else { returnfalse; } } 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 } }