標籤:pre read method ftp bin orm env 名稱 androi
現在讀寫檔案在Android原生態應該不在話下了。但是xamarin.forms應該如何用呢
1 //擷取檔案的名稱含有尾碼2 string strName = Path.GetFileName(strPath);3 strPath = "ftp://" + builder.UserName + ":" + builder.Password + "@" + builder.Host + strPath;4 builder.AllPath = strPath;5 //global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath :得到安卓的根目錄6 //Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)::得到安卓data目錄7 var path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);8 //建立檔案9 System.IO.Directory.CreateDirectory(path);
可是我運行半天在手機上都沒有找到我檔案。原來是沒有許可權。如何加許可權呢!如在安卓項目裡有個Properties的檔案下有個AndroidManifest.xml的檔案。在<application android:label="cardionNet2.Android"></application> 下加
1 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />2 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
這兩句就好。
之後如何用ftp下載檔案呢。
1 FtpWebRequest reqFTP = null;//Ftp請求 2 FileStream saveStream = null;//Ftp檔案流 3 Stream ftpStream = null;//Ftp傳輸串流 4 FtpWebResponse response = null;//Ftp響應 5 try 6 { 7 var sss = new Uri(builder.Path); 8 9 //建立要儲存的檔案10 saveStream = new FileStream(savePath, FileMode.Create);11 //下載檔案設定12 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(builder.AllPath)); 13 reqFTP.Credentials = new NetworkCredential(builder.UserName, builder.Password);14 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;15 reqFTP.UseBinary = true;16 //開始請求17 response = (FtpWebResponse)reqFTP.GetResponse();18 //開始下載19 ftpStream = response.GetResponseStream();20 //將下載內容存入檔案流21 int bufferSize = 65535;22 int readCount;23 byte[] buffer = new byte[bufferSize];24 readCount = ftpStream.Read(buffer, 0, bufferSize);25 while (readCount > 0)26 {27 saveStream.Write(buffer, 0, readCount);28 readCount = ftpStream.Read(buffer, 0, bufferSize);29 }30 }31 catch (WebException webEx)32 {33 throw webEx;34 }35 catch (Exception ex)36 {37 throw ex;38 }39 finally40 {41 //釋放資源42 if (ftpStream != null) ftpStream.Close();43 if (saveStream != null) saveStream.Close();44 if (response != null) response.Close();45 }
趨勢xamarin的ftp下載檔案和c#是一樣的關鍵在於如何在手機上建立檔案。
關於xamarin.forms Android建立檔案與寫檔案 (ftp)