File access with Xamarin.Android - Microsoft Docs
文章推薦指數: 80 %
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:
publicasyncTask
延伸文章資訊
- 1Android Development — Working with Internal Storage and ...
Internal Storage: Internal storage is a closed non-shareable space which is always available on y...
- 2Get External Storage Directory Android Example - 11zon
- 3Data and file storage overview | Android Developers
Android provides two types of physical storage locations: internal storage and external storage. ...
- 4How to get absolute path of Internal Storage in Android - Code ...
Internal Storage PathConsider the above picture. It shows the folders and file in internal storag...
- 5[Android] 12-2 Internal Storage - 給你魚竿
官網https://developer.android.com/training/basics/data-storage/files.html ... 可以看到file path = /data...