关于xamarin.forms Android创建文件与写文件 (ftp)

现在读写文件在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的文件。在 下加

1 "android.permission.READ_EXTERNAL_STORAGE" />
2 "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             finally
40             {
41                 //释放资源
42                 if (ftpStream != null) ftpStream.Close();
43                 if (saveStream != null) saveStream.Close();
44                 if (response != null) response.Close();
45             }

趋势xamarin的ftp下载文件和c#是一样的关键在于如何在手机上建立文件。

转载于:https://www.cnblogs.com/lanmaokomi/p/7463798.html

你可能感兴趣的:(关于xamarin.forms Android创建文件与写文件 (ftp))