我正在使用Xamaring表单,我正在尝试将所选图像路径复制到智能手机上的其他位置,但无法正常工作。 任何想法为什么以及如何解决它?
private async Task btn_AddImg_ClickedAsync(object sender, EventArgs e)
{
var file = await CrossFilePicker.Current.PickFileAsync();
if (file != null)
{
Error.IsVisible = true;
Error.Text = file.FilePath;
var dirToCreate = Path.Combine(Android.App.Application.Context.FilesDir.AbsolutePath, "WightLossPersonal");
if (!Directory.Exists(dirToCreate))
{
var x= Directory.CreateDirectory(dirToCreate);
System.IO.File.Copy(file.FilePath, dirToCreate, true);
}
else
{
System.IO.File.Copy(file.FilePath, dirToCreate, true);
}
}
}
在我的清单中,我获得了权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
错误讯息:
“/ data / user / 0 / com.companyname.WightLoss / files / WightLossPersonal是一个目录”
答案 0 :(得分:1)
你的主要问题是你没有在新目录中传递文件名。 所以这就像你试图复制dir本身,而不是文件!
基本上你必须将文件名与dir组合在一起 然后将其传递给Copy()方法。
string destFolder = Path.Combine(dirToCreate, file.Name);
System.IO.File.Copy(file.FilePath, destFolder , true);
但是让我们让代码更干净。我会对代码进行评论以便更好地理解。
private async Task btn_AddImg_ClickedAsync(object sender, EventArgs e)
{
var file = await CrossFilePicker.Current.PickFileAsync();
if (file != null)
{
Error.IsVisible = true;
Error.Text = file.FilePath;
var dirToCreate = Path.Combine(Android.App.Application.Context.FilesDir.AbsolutePath, "WightLossPersonal");
if (!Directory.Exists(dirToCreate))
{
Directory.CreateDirectory(dirToCreate);
// var x= Directory.CreateDirectory(dirToCreate); // don't need that variable x here since you don't want to use it later
//System.IO.File.Copy(file.FilePath, dirToCreate, true); No need here, will copy it in all ways down .
}
//else // you don't need else, copy the file when finishing the check.
//{
// Make a new path to compine the dir and the fileName
string destFolder = Path.Combine(dirToCreate, file.Name);
System.IO.File.Copy(file.FilePath, destFolder , true);
//}
}
}