次の方法で共有


Developing Windows 8 app: Accessing configuration files deployed as part of deployment

While developing your windows 8 app, you may need default configurations. In order to make things more generic, you may choose to keep your configuration in a separate xml to be deployed along with the app. Here, we will see how we can access a file deployed as part of deployment and use it.

In windows 8, access to folder system is provided by api's that are async in nature and 'Task' based. Therefore, we will use 'async' methods for this operation.

        private async Task<SampleData> ReadFromConfigurationFile()

        { 

         try

            {

                //get the package reference

                Windows.ApplicationModel.Package package = Windows.ApplicationModel.Package.Current;

                //get installed location detail

                Windows.Storage.StorageFolder storageFolder = package.InstalledLocation;

               // Use serializer class

                XmlSerializer serializer = new XmlSerializer(typeof(SampleData));         

                try

                {

                    //file variable

                    StorageFile sampleFile = null;

                     try

                    {

                       //Get the file

                        sampleFile = await storageFolder.GetFileAsync("ConfigurationStored.xml");

                    }             

                    catch (FileNotFoundException ex)

                    {

                        //handle exception

                    }                 

                  //open file in read mode

                   var file = await sampleFile.OpenAsync(FileAccessMode.Read);   

                   //Read stream         

                   Stream inStream = Task.Run(() => file.OpenRead()).Result;       

                   return (SampleData)serializer.Deserialize(inStream);

                }           

               catch (Exception ex)

                {

                 //handle exception 

                }

            }

           catch (Exception ex)

            {

             //handle exception

            }       

         return null;

        }

 

Note the use of await and async pattern for handling the asynchronous operation.

If you want to modify the default value and write the file back, open file in write mode and after modification save the same at the installed location.

 

More sample on file access can be found at https://code.msdn.microsoft.com/windowsapps/File-access-sample-d723e597.

Comments

  • Anonymous
    February 03, 2012
    Why Stream inStream = Task.Run(() => file.OpenRead()).Result;     and not Stream inStream = await Task.Run(() => file.OpenRead());

  • Anonymous
    February 04, 2012
    You can use await as well, depending upon the need of your application. Here, result property will ensure that data is read and then control is returned.