WP8 Development Series 3: differences between WP7 and WP8 in file I/O operations

Source: Internet
Author: User
Document directory
  • Parameters
  • Return Value
  • Remarks
  • Example

Introduction:

Microsoft stated that WP7 applications can be compatible with WP8 systems, and WP8 shares the same kernel with WIN8. This means that the applications developed during WP7 can be compatible with WP8, applications developed by WP8 can be migrated to Win8. What are the differences and commonalities between WP7 and WP8 in file I/O operations? This article will reveal you one or two.

1. File Operations for Windows Phone 7:

If we write a file on the existing wp7 development platform, we will think of the following:IsolatedStorageFile

The Code is as follows:

private void WriteFile(string fileName, string content)
{
    using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorageFile.CreateFile(fileName))
        {
            using (StreamWriter streamWriter = new StreamWriter(isolatedStorageFileStream))
            {
                streamWriter.Write(content);
            }
        }
    }
}

Read an object:

private string ReadFile(string fileName)
{
    string text;
    using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorageFile.OpenFile(fileName, FileMode.Open))
        {
            using (StreamReader streamReader = new StreamReader(isolatedStorageFileStream))
            {
                text = streamReader.ReadToEnd();
            }
        }
    }
    return text;
}

Then, you can use auxiliary tools such as IsoStoreSpy to view the content of stored files in the application.

Ii. Windows Phone 8 File Operations

Wp8 and win8 file operations are similar. If you have written file operations under win8, WP8 is naturally familiar. Two interfaces are required: IStorageFile and IStorageFolder, one is file operations and the other is directory operations. Both interfaces are in the Windwos. Storage component,

Note: WinRT asynchronous programming is widely used in windows 8 Development, so is programming in WP8.

Write File:

public async Task WriteFile(string fileName, string text)
{
    IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
 
    IStorageFile storageFile = await applicationFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
 
    using (Stream stream = await storageFile.OpenStreamForWriteAsync())
    {
        byte[] content = Encoding.UTF8.GetBytes(text);
        await stream.WriteAsync(content, 0, content.Length);
    }
}

Read files:

public async Task<string> ReadFile(string fileName)
{
    string text;
    IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
 
    IStorageFile storageFile = await applicationFolder.GetFileAsync(fileName);
 
    IRandomAccessStream accessStream = await storageFile.OpenReadAsync();
 
    using (Stream stream = accessStream.AsStreamForRead((int)accessStream.Size))
    {
        byte[] content = new byte[stream.Length];
        await stream.ReadAsync(content, 0, (int) stream.Length);
 
        text = Encoding.UTF8.GetString(content, 0, content.Length);
    }
    return text;
}

OK. After writing the operation file method, you can call it at the business layer. The method is as follows:

Await WriteFile ("TestWP8IO.txt", "test WP8 and WP7 file operations ");
string text = await ReadFile("TestWP8IO.txt")

Iii. compatibility issues

The code above briefly describes the file write and read operations on WP7 and WP8 platforms. You may think: "My definition of the file directory structure in WP7 applications, is it the same in WP8?" In fact, the two are a little different. This difference is also one of the elements that must be considered during the migration from WP7 to WP8 in the future.

Create the userinfo.txt file in wp7. the file directory structure in the isolated storage area is as follows:

C: \ Data \ Users \ defaappappaccount \ AppData \ {ProductID} \ Local \ IsolatedStore\ Userinfo.txt

In WP8, create the same file. The file storage directory structure is as follows:

C: \ Data \ Users \ DefaultAppAccount \ AppData \ {ProductID} \ Local \Userinfo.txt

We can intuitively see the difference between the two. This means that when using the existing WP7 code in WP8 development, if you do not want to change the original file directory structure, you must first obtain the WP7 isolated storage directory. that is:

IStorageFolder applicationFolder =await ApplicationData.Current.LocalFolder.GetFolderAsync("IsolatedStore");

Finally, we want to explain the following:

If you want to be "lazy" or reduce the development workload, let's take a look at what I mentioned above. However, I suggest developers, preferably brand new applications based on the WP8 platform, after all, this means that you can also quickly deploy it in Win8.

Address: http://jasonwei.com/archives/463

Continued:

Open the file (you need to install such an application on your phone, such as PDF | OneNote)

 IAsyncOperation<StorageFile> getFile = ApplicationData.Current.LocalFolder.GetFileAsync(filePath); getFile.Completed = (IAsyncOperation<StorageFile> asyncInfo, AsyncStatus asyncStatus) =>            {                if (asyncStatus == AsyncStatus.Completed)                {                    IStorageFile file = getFile.GetResults();                    IAsyncOperation<bool> isLaunch = Windows.System.Launcher.LaunchFileAsync(file);                    isLaunch.Completed = (IAsyncOperation<bool> asyncInfo_launch, AsyncStatus asyncStatus_launch) =>                    {                        if (asyncStatus_launch == AsyncStatus.Completed)                        {                            Debug.WriteLine("isLaunch:" + isLaunch);                        }                     };                }            };
Launcher. LaunchFileAsync (IStorageFile) | launchFileAsync (IStorageFile) Method (Windows)

Start the Default Application associated with the specified file.

Public static IAsyncOperation <bool> LaunchFileAsync (IStorageFile file)

Parameters
File

Type:IStorageFile

File.

Return Value

Type:IAsyncOperation <Boolean>

Generation operation.

Remarks

When calling an API, The called application must be visible to the user.

This API also has several restrictions on the types of files it can generate. Many file types that contain executable code, such as. exe,. msi, and. js files, are blocked at startup. Malicious files modify the system, which can protect users from potential malicious files.

If the API fails to be generated for any of the above reasons, the API is successful and returned from its Asynchronous Operation "FALSE. Because it cannot query whether the above restrictions are applied to the current generation, calling the application should not assume that the application has been successfully generated, but provide a rollback mechanism when the failure occurs. The possible solution is to ask the user to save the file and instruct the user to open it on the desktop.

 

SetLauncherOptions. DisplayApplicationPicker | displayApplicationPickerAttribute.

 

To display a warning that the file may be insecure, SetLauncherOptions. TreatAsUntrusted | treatAsUntrustedAttribute.

 

The file is passed to the associated application. If the associated application is a desktop application, the file is transmitted using the shell execution mechanism.

Example

This example usesLaunchFileAsync (IStorageFile) | launchFileAsync (IStorageFile)Generate files contained in the application package.

async void DefaultLaunch(){   // Path to the file in the app package to launch   string imageFile = @"images\test.png";   var file = wait Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);   if (file != null)   {      // Launch the retrieved file      var success = await Windows.System.Launcher.LaunchFileAsync(file);      if (success)      {         // File launched      }      else      {         // File launch failed      }   }   else   {      // Could not find file   }}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.