我正在尝试从字节数组生成PDF。但它给出的问题是“访问路径被拒绝”。 我已经在清单文件中给出了权限。我发送我的代码块请检查一下,并给出一些建议和反馈,以便我可以完成它。
private void ObjbtnViewSlip_Click(object sender, EventArgs e)
{
var result = objPaySlipViewModel.GetPaySlipByte(GlobalApplicationSession.EmployeeCode, GlobalApplicationSession.CompanyId, selectedPeriod);
if (File.Exists(Android.OS.Environment.DirectoryDownloads + "/RSI/PaySlip/temp.pdf") == false)
{
Directory.CreateDirectory(Android.OS.Environment.DirectoryDownloads + "/RSI/PaySlip/");
File.Create(Android.OS.Environment.DirectoryDownloads + "/RSI/PaySlip/temp.pdf");
System.IO.File.WriteAllBytes(Android.OS.Environment.DirectoryDownloads + "/RSI/PaySlip/", result);
}
}
答案 0 :(得分:2)
首先,您提供的路径不正确。 Android.OS.Environment.DirectoryDownloads只会返回"下载"
修改代码以获取下载文件夹的完整路径,如:
//The following will return the downloads folder path.
string directory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
string file = Path.Combine(directory, "/RSI/PaySlip/temp.pdf");
同时检查AndroidManifest.xml文件中是否提及以下内容以授予应用程序权限。
uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
答案 1 :(得分:0)
string localStoragePath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string localFilename = Path.GetFileName(serverFileName);
string localFilePath = Path.Combine(localStoragePath, localFilename);
if (!System.IO.File.Exists(localFilePath))
{
WebClient webClient = new WebClient();
webClient.DownloadFile(serverFileName, localFilePath);
}
OpenFile(localFilePath);
});
public void OpenFile(string filePath) {
var bytes = File.ReadAllBytes(filePath);
//Copy the private file's data to the EXTERNAL PUBLIC location
string externalStorageState = global::Android.OS.Environment.ExternalStorageState;
string application = "";
string extension = System.IO.Path.GetExtension(filePath);
switch (extension.ToLower())
{
case ".doc":
case ".docx":
application = "application/msword";
break;
case ".pdf":
application = "application/pdf";
break;
case ".xls":
case ".xlsx":
application = "application/vnd.ms-excel";
break;
case ".jpg":
case ".jpeg":
case ".png":
application = "image/jpeg";
break;
default:
application = "*/*";
break;
}
var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/report" + extension;
File.WriteAllBytes(externalPath, bytes);
Java.IO.File file = new Java.IO.File(externalPath);
file.SetReadable(true);
//Android.Net.Uri uri = Android.Net.Uri.Parse("file://" + filePath);
var uri = global::Android.Net.Uri.FromFile(file);
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(uri, application);
intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
try
{
Application.Context.StartActivity(intent);
}
catch (Exception)
{
Toast.MakeText(Application.Context, "No Application Available to View PDF", ToastLength.Short).Show();
}
}