File access with Xamarin.Android - Microsoft Docs

文章推薦指數: 80 %
投票人數:10人

Android app determines the path to the file that will be manipulated, ... Because the actual paths to internal and external storage may vary ... Skiptomaincontent Thisbrowserisnolongersupported. UpgradetoMicrosoftEdgetotakeadvantageofthelatestfeatures,securityupdates,andtechnicalsupport. DownloadMicrosoftEdge Moreinfo Contents Exitfocusmode Save Edit Share Twitter LinkedIn Facebook Email Tableofcontents FileStorageandAccesswithXamarin.Android 09/29/2020 7minutestoread d D d c n +3 Isthispagehelpful? Pleaserateyourexperience Yes No Anyadditionalfeedback? FeedbackwillbesenttoMicrosoft:Bypressingthesubmitbutton,yourfeedbackwillbeusedtoimproveMicrosoftproductsandservices.Privacypolicy. Submit Thankyou. Inthisarticle AcommonrequirementforAndroidappsistomanipulatefiles–savingpictures,downloadingdocuments,orexportingdatatosharewithotherprograms.Android(whichisbasedonLinux)supportsthisbyprovidingspaceforfilestorage.Androidgroupsthefilesystemintotwodifferenttypesofstorage: InternalStorage–thisisaportionofthefilesystemthatcanbeaccessedonlybytheapplicationortheoperatingsystem. ExternalStorage–thisisapartitionforthestorageoffilesthatisaccessiblebyallapps,theuser,andpossiblyotherdevices.Onsomedevices,externalstoragemayberemovable(suchasanSDcard). Thesegroupingsareconceptualonly,anddon'tnecessarilyrefertoasinglepartitionordirectoryonthedevice.AnAndroiddevicewillalwaysprovidepartitionforinternalstorageandexternalstorage.Itispossiblethatcertaindevicesmayhavemultiplepartitionsthatareconsideredtobeexternalstorage.RegardlessofthepartitiontheAPIsforreading,writing,orcreatingfilesisthesame.TherearetwosetsofAPIsthataXamarin.Androidapplicationmayuseforfileaccess: The.NETAPIs(providedbyMonoandwrappedbyXamarin.Android)–TheseincludesthefilesystemhelpersprovidedbyXamarin.Essentials.The.NETAPIsprovidethebestcross-platformcompatibilityandassuchthefocusofthisguidewillbeontheseAPIs. ThenativeJavafileaccessAPIs(providedbyJavaandwrappedbyXamarin.Android)–JavaprovidesitsownAPIsforreadingandwritingfiles.Theseareacompletelyacceptablealternativetothe.NETAPIs,butarespecifictoAndroidandarenotsuitableforappsthatareintendedtobecross-platform. ReadingandwritingtofilesisalmostidenticalinXamarin.Androidasitistoanyother.NETapplication.TheXamarin.Androidappdeterminesthepathtothefilethatwillbemanipulated,thenusesstandard.NETidiomsforfileaccess.BecausetheactualpathstointernalandexternalstoragemayvaryfromdevicetodeviceorfromAndroidversiontoAndroidversion,itisnotrecommendedtohardcodethepathtothefiles.Instead,usetheXamarin.AndroidAPIstodeterminethepathtofiles.Thatway,the.NETAPIsforreadingandwritingfilesexposesthenativeAndroidAPIsthatwillhelpwithdeterminingthepathtofilesoninternalandexternalstorage. BeforediscussingtheAPIsinvolvedwithfileaccess,itisimportanttounderstandsomeofthedetailssurroundinginternalandexternalstorage.Thiswillbediscussedinthenextsection. Internalvsexternalstorage Conceptually,internalstorageandexternalstorageareverysimilar–theyarebothplacesatwhichaXamarin.Androidappmaysavefiles.ThissimilaritymaybeconfusingfordeveloperswhoarenotfamiliarwithAndroidasitisnotclearwhenanappshoulduseinternalstoragevsexternalstorage. Internalstoragereferstothenon-volatilememorythatAndroidallocatestotheoperatingsystem,APKs,andforindividualapps.Thisspaceisnotaccessibleexceptbytheoperatingsystemorapps.Androidwillallocateadirectoryintheinternalstoragepartitionforeachapp.Whentheappisuninstalled,allthefilesthatarekeptoninternalstorageinthatdirectorywillalsobedeleted.Internalstorageisbestsuitedforfilesthatareonlyaccessibletotheappandthatwillnotbesharedwithotherappsorwillhaveverylittlevalueoncetheappisuninstalled.OnAndroid6.0orhigher,filesoninternalstoragemaybeautomaticallybackedupbyGoogleusingtheAutoBackupfeatureinAndroid6.0.Internalstoragehasthefollowingdisadvantages: Filescannotbeshared. Fileswillbedeletedwhentheappisuninstalled. Thespaceavailableoninternalstoragemaybelimited. Externalstoragereferstofilestoragethatisnotinternalstorageandnotexclusivelyaccessibletoanapp.Theprimarypurposeofexternalstorageistoprovideaplacetoputfilesthataremeanttobesharedbetweenappsorthataretoolargetofitontheinternalstorage.Theadvantageofexternalstorageisthatittypicallyhasmuchmorespaceforfilesthaninternalstorage.However,externalstorageisnotalwaysguaranteedtobepresentonadeviceandmayrequirespecialpermissionfromtheusertoaccessit. Note Fordevicesthatsupportmultipleusers,Androidwillprovideeachusertheirowndirectoryonbothinternalandexternalstorage.Thisdirectoryisinaccessibletootherusersonthedevice.Thisseparationisinvisibletoappsaslongastheydonothardcodepathstofilesoninternalorexternalstorage. Asaruleofthumb,Xamarin.Androidappsshouldprefersavingtheirfilesoninternalstoragewhenitisreasonable,andrelyonexternalstoragewhenfilesneedtobesharedwithotherapps,areverylarge,orshouldberetainedeveniftheappisuninstalled.Forexample,aconfigurationfileisbestsuitedforainternalstorageasithasnoimportanceexcepttotheappthatcreatesit.Incontrast,photosareagoodcandidateforexternalstorage.Theycanbeverylargeandinmanycasestheusermaywanttosharethemoraccessthemeveniftheappisuninstalled. Thisguidewillfocusoninternalstorage.PleaseseetheguideExternalstoragefordetailsonusingexternalstorageinaXamarin.Androidapplication. Workingwithinternalstorage Theinternalstoragedirectoryforanapplicationisdeterminedbytheoperatingsystem,andisexposedtoAndroidappsbytheAndroid.Content.Context.FilesDirproperty.ThiswillreturnaJava.IO.FileobjectrepresentingthedirectorythatAndroidhasdedicatedexclusivelyfortheapp.Forexample,anappwiththepackagenamecom.companynametheinternalstoragedirectorymightbe: /data/user/0/com.companyname/files ThisdocumentwillrefertotheinternalstoragedirectoryasINTERNAL_STORAGE. Important TheexactpathtotheinternalstoragedirectorycanvaryfromdevicetodeviceandbetweenversionsofAndroid.Becauseofthis,appsmustnothardcodethepathtotheinternalfilesstoragedirectory,andinsteadusetheXamarin.AndroidAPIs,suchasSystem.Environment.GetFolderPath(). Tomaximizecodesharing,Xamarin.Androidapps(orXamarin.FormsappstargetingXamarin.Android)shouldusetheSystem.Environment.GetFolderPath()method.InXamarin.Android,thismethodwillreturnastringforadirectorythatisthesamelocationasAndroid.Content.Context.FilesDir.Thismethodtakesanenum,System.Environment.SpecialFolder,whichisusedtoidentifyasetofenumeratedconstantsthatrepresentthepathsofspecialfoldersusedbytheoperatingsystem.NotalloftheSystem.Environment.SpecialFoldervalueswillmaptoavaliddirectoryonXamarin.Android.ThefollowingtabledescribeswhatpathcanbeexpectedforagivenvalueofSystem.Environment.SpecialFolder: System.Environment.SpecialFolder Path ApplicationData INTERNAL_STORAGE/.config Desktop INTERNAL_STORAGE/Desktop LocalApplicationData INTERNAL_STORAGE/.local/share MyDocuments INTERNAL_STORAGE MyMusic INTERNAL_STORAGE/Music MyPictures INTERNAL_STORAGE/Pictures MyVideos INTERNAL_STORAGE/Videos Personal INTERNAL_STORAGE Fonts INTERNAL_STORAGE/.fonts Templates INTERNAL_STORAGE/Templates CommonApplicationData /usr/share CommonApplicationData /usr/share ReadingorWritingtofilesoninternalstorage AnyoftheC#APIsforwritingtoafilearesufficient;allthatisnecessaryistogetthepathtothefilethatisinthedirectoryallocatedtotheapplication.Itisstronglyrecommendedthattheasyncversionsofthe.NETAPIsareusedtominimizeanyissuesthatmaybeassociatewithfileaccessblockingthemainthread. ThiscodesnippetisoneexampleofwritinganintegertoaUTF-8textfiletotheinternalstoragedirectoryofanapplication: publicasyncTaskSaveCountAsync(intcount) { varbackingFile=Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),"count.txt"); using(varwriter=File.CreateText(backingFile)) { awaitwriter.WriteLineAsync(count.ToString()); } } Thenextcodesnippetprovidesonewaytoreadanintegervaluethatwasstoredinatextfile: publicasyncTaskReadCountAsync() { varbackingFile=Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),"count.txt"); if(backingFile==null||!File.Exists(backingFile)) { return0; } varcount=0; using(varreader=newStreamReader(backingFile,true)) { stringline; while((line=awaitreader.ReadLineAsync())!=null) { if(int.TryParse(line,outvarnewcount)) { count=newcount; } } } returncount; } UsingXamarin.Essentials–FileSystemHelpers Xamarin.EssentialsisasetofAPIsforwritingcross-platformcompatiblecode.TheFileSystemHelpersisaclassthatcontainsaseriesofhelperstosimplifylocatingtheapplication'scacheanddatadirectories.Thiscodesnippetprovidesanexampleofhowtofindtheinternalstoragedirectoryandthecachedirectoryforanapp: //Getthepathtoafileoninternalstorage varbackingFile=Path.Combine(Xamarin.Essentials.FileSystem.AppDataDirectory,"count.txt"); //Getthepathtoafileinthecachedirectory varcacheFile=Path.Combine(Xamarin.Essentials.FileSystem.CacheDirectory,"count.txt"); HidingfilesfromtheMediaStore TheMediaStoreisanAndroidcomponentthatcollectsmetadataaboutmediafiles(videos,music,images)onanAndroiddevice.ItspurposeissimplifythesharingofthesefilesacrossallAndroidappsonthedevice. Privatefileswillnotshowupasshareablemedia.Forexample,ifanappsavesapicturetoitsprivateexternalstorage,thenthatfilewillnotbepickedupbythemediascanner(MediaStore). PublicfileswillbepickedupbyMediaStore.Directoriesthathaveazerobytefilename.NOMEDIAwillnotbescannedbyMediaStore. RelatedLinks ExternalStorage Savefilesondevicestorage Xamarin.EssentialsFileSystemHelpers BackupuserdatawithAutoBackup AdoptableStorage Inthisarticle



請為這篇文章評分?