UWP:检查,创建数据并将其添加到文件

时间:2017-01-21 13:43:59

标签: vb.net uwp

我创建了一个函数来检查文件" test.txt"存在:

Public Function CheckIfFileExists(sFileName As String) As Integer

     Dim Location As Windows.Storage.StorageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation
     Dim lstfiles = Location.GetFilesAsync(Search.CommonFileQuery.OrderByName)
     Dim foundfiles = lstfiles.GetResults
     Dim bFound As Integer
     bFound = 0

     If foundfiles IsNot Nothing Then

         For Each sFile In foundfiles
             If sFile.Name = sFileName Then
                 bFound = 1
                 Exit For
             End If
        Next
     End If
     Return bFound

End Function

现在,当我第一次在主函数中调用CheckIfFileExists(FILENAME)时,例如

CheckIfFileExists("test.txt")

,它返回一个" System.Runtime.InteropServices.COMException"说我在意外的时间调用了这个方法。

Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.ni.dll

是否与我在同步函数中使用异步函数有关?

如果是,我如何修改我的功能以异步工作?

谢谢!

1 个答案:

答案 0 :(得分:0)

  

是否与我在同步函数中使用异步函数有关?

是的,您应该始终等待异步GetFilesAsync方法:

Public Async Function CheckIfFileExists(sFileName As String) As Task(Of Integer)

    Dim Location As Windows.Storage.StorageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation
    Dim lstfiles = Await Location.GetFilesAsync(Search.CommonFileQuery.OrderByName)
    Dim foundfiles = lstfiles
    Dim bFound As Integer
    bFound = 0

    If foundfiles IsNot Nothing Then
        For Each sFile In foundfiles
            If sFile.Name = sFileName Then
                bFound = 1
                Exit For
            End If
        Next
    End If
    Return bFound
End Function

CheckIfFileExists方法:

Dim b As Boolean = Await CheckIfFileExists("test.txt")