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 Tutorial: Android Internal Storage | CodeVoila
The absolute path of internal storage folder is: /data/data/<YOUR_APP_PACKAGE_NAME>/files/ . Call...
- 2Internal memory storage path android 9 - OnePlus Community
Hello, i make apps for android phones and i ran into the problem with obtaining internal memory s...
- 3How to get file path from Internal Storage in Android? - 11zon
Android Internal storage is used to read and write data to the internal memory that store data pr...
- 4How to Manage Files and Use the File System on Android - HowToGeek
- 5File access with Xamarin.Android - Microsoft Docs
Android app determines the path to the file that will be manipulated, ... Because the actual path...