WindowsPhone向独立存储中读取写入文件

Posted by baicai on September 16, 2013
public static class DataRW
{
    public static void WriteToFile(string content, string filename)
    {
        try
        {
            // Get the local folder.
            System.IO.IsolatedStorage.IsolatedStorageFile local =
                System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();

            // Create a new folder named DataFolder.
            if (!local.DirectoryExists("DataFolder"))
                local.CreateDirectory("DataFolder");

            // Create a new file named DataFile.txt.
            using (var isoFileStream =
                    new System.IO.IsolatedStorage.IsolatedStorageFileStream(
                        "DataFolder\\" + filename,
                        System.IO.FileMode.Create,
                            local))
            {
                // Write the data from the textbox.
                using (var isoFileWriter = new System.IO.StreamWriter(isoFileStream))
                {
                    isoFileWriter.WriteLine(content);
                }
            }
        }
        catch { }
    }
    public static string ReadFile(string filename)
    {
        try
        {
            // Obtain a virtual store for the application.
            System.IO.IsolatedStorage.IsolatedStorageFile local =
                System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();

            if (local.FileExists("DataFolder\\" + filename))
            {
                // Specify the file path and options.
                using (var isoFileStream = new System.IO.IsolatedStorage.IsolatedStorageFileStream
                            ("DataFolder\\" + filename, System.IO.FileMode.Open, local))
                {
                    // Read the data.
                    using (var isoFileReader = new System.IO.StreamReader(isoFileStream))
                    {
                        return isoFileReader.ReadLine();
                    }
                }
            }
            else
            {
                return null;
            }
        }
        catch { return null; }
    }
}