我需要一个文件夹内所有文件的文件详细信息(广告它的子文件夹)。为此,我编写了一个递归函数。
private async Task getallfiles(StorageFolder appfolder)
{
IReadOnlyList<StorageFile> sortedItems1 = await appfolder.GetFilesAsync();
if (sortedItems1.Count > 0)
{
foreach (StorageFile file in sortedItems1)
CopyContentToIsolatedStorage(file.Path);
}
IReadOnlyList<StorageFolder> sorteditems2 = await appfolder.GetFoldersAsync();
if (sorteditems2.Count > 0)
{
foreach (StorageFolder folder in sorteditems2)
await getallfiles(folder);
}
}现在,当我使用作为参数传递的根文件夹来调用这个函数时,我只获取sorteditems中根文件夹中的文件,这是一个全局变量。我尝试将不同的文件夹作为参数传递,但是每次返回的排序项只包含父文件夹中的文件,子文件夹中没有一个文件。
是我遗漏了什么,还是代码在逻辑上有问题。任何帮助都将不胜感激。
我得到的例外-它可能有助于找出问题:
{System.NullReferenceException:未设置为对象实例的对象引用。在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task ()--从抛出异常的前一个位置--在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task任务上抛出异常的堆栈跟踪的末尾--在Appzillon.MainPage.d__36.MoveNext()处的System.Runtime.CompilerServices.TaskAwaiter.GetResult()上--从抛出异常的前一个位置的堆栈跟踪结束-在System.Runtime.CompilerServices.AsyncMethodBuilderCore.b__0(Object状态下)}。
另外,函数CopyContentToIsolatedStorage如下:
public static void CopyContentToIsolatedStorage(string file)
{
// Obtain the virtual store for the application.
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
if (iso.FileExists(file))
return;
var fullDirectory = System.IO.Path.GetDirectoryName(file);
if (!iso.DirectoryExists(fullDirectory))
iso.CreateDirectory(fullDirectory);
// Create a stream for the file in the installation folder.
using (Stream input = Application.GetResourceStream(new Uri(file, UriKind.Relative)).Stream)
{
// Create a stream for the new file in isolated storage.
using (IsolatedStorageFileStream output = iso.CreateFile(file))
{
// Initialize the buffer.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the file from the installation folder to isolated storage.
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
}
}
}编辑:更新的代码,并添加了我得到的异常。我只获得根文件夹文件的原因是,正如kennyzx所提到的那样,我将sortedItems作为Readonly。但是,即使在尝试了他修改的代码,实际上也将其更改为上面的更新代码之后,我也遇到了一些问题。请看我对kennyzx的回答的评论..。
问候
发布于 2014-11-22 11:22:05
您可能已经将sortedItems声明为IReadOnlyList<StorageFile>,因此不能修改sortedItems (这就是为什么它在代码中称为IReadOnlyList<StorageFile>,Concat方法将sortedItems和sortedItems1组合在一起生成一个新列表),这些文件实际上没有添加到sortedItems中。
因此,首先将sortedItems声明为List<StorageFile>,它支持向本身添加另一个列表。
在递归调用该方法之前,您将忘记await关键字。
List<StorageFile> sortedItems = new List<StorageFile>();
private async Task getallfiles(StorageFolder appfolder)
{
IReadOnlyList<StorageFile> sortedItems1 = await appfolder.GetFilesAsync();
sortedItems.AddRange(sortedItems1);
IReadOnlyList<StorageFolder> sorteditems2 = await appfolder.GetFoldersAsync();
if (sorteditems2.Count > 0)
{
foreach (StorageFolder folder in sorteditems2)
await getallfiles(folder); //add await
}
}https://stackoverflow.com/questions/27075522
复制相似问题