none
FileIO equivalent RRS feed

  • Question

  • Hi,

    I have an app for windows8 that I am converting to windows phone.
    It contains data that is stored in files and comes to the UI via a view model.
    Everything was going swimmingly (too good as it happens) until I ran into a problem.

    That problem is that there is no Windows.Storage.FileIO for windows phone.

    I'm using a StorageHelper that I obtained from an online example and it works great for win8 apps, just not for phones.

    This is the StorageHelper

    Imports System.Text
    Imports System.Threading.Tasks
    
    Public Class StorageHelper
        Private Sub New()
        End Sub
    
    
        ''' <summary>Returns if a file is found in the specified storage strategy</summary>
        ''' <param name="key">Path of the file in storage</param>
        ''' <param name="location">Location storage strategy</param>
        ''' <returns>Boolean: true if found, false if not found</returns>
        Public Shared Async Function FileExistsAsync(ByVal key As String, Optional ByVal location As StorageStrategies = StorageStrategies.Local) As Task(Of Boolean)
            Return (Await GetIfFileExistsAsync(key, location)) IsNot Nothing
        End Function
    
        Public Shared Async Function FileExistsAsync(ByVal key As String, ByVal folder As Windows.Storage.StorageFolder) As Task(Of Boolean)
            Return (Await GetIfFileExistsAsync(key, folder)) IsNot Nothing
        End Function
    
        ''' <summary>Deletes a file in the specified storage strategy</summary>
        ''' <param name="key">Path of the file in storage</param>
        ''' <param name="location">Location storage strategy</param>
        Public Shared Async Function DeleteFileAsync(ByVal key As String, Optional ByVal location As StorageStrategies = StorageStrategies.Local) As Task(Of Boolean)
            Dim _File = Await GetIfFileExistsAsync(key, location)
            If _File IsNot Nothing Then
                Await _File.DeleteAsync()
            End If
            Return Not (Await FileExistsAsync(key, location))
        End Function
    
        ''' <summary>Reads and deserializes a file into specified type T</summary>
        ''' <typeparam name="T">Specified type into which to deserialize file content</typeparam>
        ''' <param name="key">Path to the file in storage</param>
        ''' <param name="location">Location storage strategy</param>
        ''' <returns>Specified type T</returns>
        Public Shared Async Function ReadFileAsync(Of T)(ByVal key As String, Optional ByVal location As StorageStrategies = StorageStrategies.Local) As Task(Of T)
            Try
                ' fetch file
                Dim _File = Await GetIfFileExistsAsync(key, location)
                If _File Is Nothing Then
                    Return Nothing
                End If
                ' read content
                Dim _String = Await Windows.Storage.FileIO.ReadTextAsync(_File)
                ' convert to obj
                Dim _Result = Deserialize(Of T)(_String)
                Return _Result
            Catch e1 As Exception
                Throw
            End Try
        End Function
    
        ''' <summary>Serializes an object and write to file in specified storage strategy</summary>
        ''' <typeparam name="T">Specified type of object to serialize</typeparam>
        ''' <param name="key">Path to the file in storage</param>
        ''' <param name="value">Instance of object to be serialized and written</param>
        ''' <param name="location">Location storage strategy</param>
        Public Shared Async Function WriteFileAsync(Of T)(ByVal key As String, ByVal value As T, Optional ByVal location As StorageStrategies = StorageStrategies.Local) As Task(Of Boolean)
            ' create file
            Dim _File = Await CreateFileAsync(key, location, Windows.Storage.CreationCollisionOption.ReplaceExisting)
            ' convert to string
            Dim _String = Serialize(value)
            ' save string to file
            Await Windows.Storage.FileIO.WriteTextAsync(_File, _String)
            ' result
            Return Await FileExistsAsync(key, location)
        End Function
    
        Private Shared Async Function CreateFileAsync(ByVal key As String, Optional ByVal location As StorageStrategies = StorageStrategies.Local, Optional ByVal [option] As Windows.Storage.CreationCollisionOption = Windows.Storage.CreationCollisionOption.OpenIfExists) As Task(Of Windows.Storage.StorageFile)
            Select Case location
                Case StorageStrategies.Local
                    Return Await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(key, [option])
                Case StorageStrategies.Roaming
                    Return Await Windows.Storage.ApplicationData.Current.RoamingFolder.CreateFileAsync(key, [option])
                Case StorageStrategies.Temporary
                    Return Await Windows.Storage.ApplicationData.Current.TemporaryFolder.CreateFileAsync(key, [option])
                Case Else
                    Throw New NotSupportedException(location.ToString())
            End Select
        End Function
    
        Private Shared Async Function GetIfFileExistsAsync(ByVal key As String, ByVal folder As Windows.Storage.StorageFolder, Optional ByVal [option] As Windows.Storage.CreationCollisionOption = Windows.Storage.CreationCollisionOption.FailIfExists) As Task(Of Windows.Storage.StorageFile)
            Dim retval As Windows.Storage.StorageFile
            Try
                retval = Await folder.GetFileAsync(key)
            Catch e1 As System.IO.FileNotFoundException
                System.Diagnostics.Debug.WriteLine("GetIfFileExistsAsync:FileNotFoundException")
                Return Nothing
            End Try
            Return retval
        End Function
    
        ''' <summary>Returns a file if it is found in the specified storage strategy</summary>
        ''' <param name="key">Path of the file in storage</param>
        ''' <param name="location">Location storage strategy</param>
        ''' <returns>StorageFile</returns>
        Private Shared Async Function GetIfFileExistsAsync(ByVal key As String, Optional ByVal location As StorageStrategies = StorageStrategies.Local, Optional ByVal [option] As Windows.Storage.CreationCollisionOption = Windows.Storage.CreationCollisionOption.FailIfExists) As Task(Of Windows.Storage.StorageFile)
            Dim retval As Windows.Storage.StorageFile
            Try
                Select Case location
                    Case StorageStrategies.Local
                        retval = Await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(key)
                    Case StorageStrategies.Roaming
                        retval = Await Windows.Storage.ApplicationData.Current.RoamingFolder.GetFileAsync(key)
                    Case StorageStrategies.Temporary
                        retval = Await Windows.Storage.ApplicationData.Current.TemporaryFolder.GetFileAsync(key)
                    Case Else
                        Throw New NotSupportedException(location.ToString())
                End Select
            Catch e1 As System.IO.FileNotFoundException
                System.Diagnostics.Debug.WriteLine("GetIfFileExistsAsync:FileNotFoundException")
                Return Nothing
            End Try
    
            Return retval
        End Function
    
    
        ''' <summary>Serializes the specified object as a JSON string</summary>
        ''' <param name="objectToSerialize">Specified object to serialize</param>
        ''' <returns>JSON string of serialzied object</returns>
        Private Shared Function Serialize(ByVal objectToSerialize As Object) As String
            Using _Stream As New System.IO.MemoryStream()
                Try
                    Dim _Serializer = New System.Runtime.Serialization.Json.DataContractJsonSerializer(objectToSerialize.GetType())
                    _Serializer.WriteObject(_Stream, objectToSerialize)
                    _Stream.Position = 0
                    Dim _Reader As New System.IO.StreamReader(_Stream)
                    Return _Reader.ReadToEnd()
                Catch e As Exception
                    System.Diagnostics.Debug.WriteLine("Serialize:" & e.Message)
                    Return String.Empty
                End Try
            End Using
        End Function
    
        ''' <summary>Deserializes the JSON string as a specified object</summary>
        ''' <typeparam name="T">Specified type of target object</typeparam>
        ''' <param name="jsonString">JSON string source</param>
        ''' <returns>Object of specified type</returns>
        Private Shared Function Deserialize(Of T)(ByVal jsonString As String) As T
            Using _Stream As New System.IO.MemoryStream(Encoding.Unicode.GetBytes(jsonString))
                Try
                    Dim _Serializer = New System.Runtime.Serialization.Json.DataContractJsonSerializer(GetType(T))
                    Return CType(_Serializer.ReadObject(_Stream), T)
                Catch e1 As Exception
                    Throw
                End Try
            End Using
        End Function
    
        Public Enum StorageStrategies
            ''' <summary>Local, isolated folder</summary>
            Local
            ''' <summary>Cloud, isolated folder. 100k cumulative limit.</summary>
            Roaming
            ''' <summary>Local, temporary folder (not for settings)</summary>
            Temporary
        End Enum
    
    End Class
    

    Is there a way I can get this to work with windows phone?
    I am aware there are other methods but the final aim is to get both apps taking to one another so I want them to work in the same way.

    Any help would be gratefully received.

    Thanks

    Tuesday, April 29, 2014 3:28 PM

All replies

  • Since the code works fine for Windows 8, you should be pretty much able to port over that code to Windows Phone 8.1 based Windows Runtime app.

    If you plan to target the regular Windows Phone 8 environment, then you need to use the Windows Phone 8 specific File IO (which is different than the Windows Runtime File IO).


    Windows Store Developer Solutions, follow us on Twitter: @WSDevSol|| Want more solutions? See our blog

    Wednesday, April 30, 2014 12:25 AM
    Moderator
  • Thanks for the reply.

    I didnt really want to have to wait until 8.1 is released to publish the app so was hoping to target the current wp8.

    Is there a substitute i can use for FileIO?

    I'm guessing that there is something similar that i would need to use to get it to work on the phone, I just cant seem to find it so would love a nudge in the right direction.

    Wednesday, April 30, 2014 7:35 AM