File operations in Windows Phone 8.1

This article describes about the File operations, create, write, delete file and file picker to select multiple files in Windows Phone 8.1.

Create a universal app project; by creating a Universal app project, you will get two projects, project for windows store and project for Windows Phone by sharing the shared project.

Note: Make sure you install VS 2013 with Update 2 for creating a Universal app project.

Create a helper class to handle all file operations,

Write to File:

public static async Task WriteToLocalFile(string fileName, string content)
         {
             // saves the string 'content' to a file 'filename' in the app's local storage folder
            byte[] fileBytes = Encoding.UTF8.GetBytes(content.ToCharArray());

             // create a file with the given filename in the local folder; replace any existing file with the same name
            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            // write the char array created from the content string into the file
            using (var stream = await file.OpenStreamForWriteAsync())
             {
                 stream.Write(fileBytes, 0, fileBytes.Length);
            }
        }

From above function, accepts the filename and content as input parameters. Here, defining the path as ApplicationData.Current.LocalFolder where the file has to be created.

Read File:
public static async Task<string> ReadFromLocalFile(string filename)
         {
             // reads the contents of file 'filename' in the app's local storage folder and returns it as a string

             // access the local folder
            var local = ApplicationData.Current.LocalFolder;
             // open the file 'filename' for reading
            Stream stream = await local.OpenStreamForReadAsync(filename);
            string text;

             // copy the file contents into the string 'text'
            using (var reader = new StreamReader(stream))
            {
                text = reader.ReadToEnd();
             }

             return text;
        }

From above function, accepting the filename as input parameter, access the file from local folder and then read the content.

Delete File:
public static async void DeleteFile(string fileName)
        {
            try
            {
                 if (await FileExists(fileName))
                {
                    var local = ApplicationData.Current.LocalFolder;
                    var file = await local.GetFileAsync(fileName);
                    await file.DeleteAsync();
                 }
             }
             catch
             {
             }
         }
public static async Task<bool> FileExists(string fileName)
         {
             try
            {
                var local = ApplicationData.Current.LocalFolder;
                var file = await local.GetFileAsync(fileName);
            }
            catch { return false; }
            return true;
        }

From above function, first check whether the file exists in local folder by file name. If exists, then get the file and delete from local folder.
Now, create a simple UI for testing these file operations.

<StackPanel Height="300" Margin="10" VerticalAlignment="Top">
            <TextBox Name="txtContent" Width="300" Height="100" TextWrapping="Wrap"></TextBox>
            <StackPanel Orientation="Horizontal">
                 <Button Name="btnCreate" Content="Create File" Margin="5" Click="btnCreate_Click" ></Button>
                 <Button Name="btnRead" Content="Read File" Margin="5" Click="btnRead_Click"></Button>
                 <Button Name="btnDelete" Content="Delete File" Margin="5" Click="btnDelete_Click"></Button>
                 
             </StackPanel>
            <Button Name="btnFilePicker" Content="File Picker" Margin="5" Click="btnFilePicker_Click"></Button>
        </StackPanel>

In Create File button click event, call the WriteToLocalFile function to create a file and then write the content in to file.
private async void btnCreate_Click(object sender, RoutedEventArgs e)
         {
             if (!string.IsNullOrEmpty(txtContent.Text))
            {
                await FileHelper.WriteToLocalFile("Test1.txt", txtContent.Text);

                 this.txtContent.Text = string.Empty;
            }
        }

In Read File button click event, add below piece of code to read the content by the file name.
private async void btnRead_Click(object sender, RoutedEventArgs e)
         {
             this.txtContent.Text = await FileHelper.ReadFromLocalFile("Test1.txt");
        }

As well, add below code for delete click event.

  private void btnDelete_Click(object sender, RoutedEventArgs e)
         {
             FileHelper.DeleteFile("Test1.txt");
        }

File Picker:
In File Picker button click event, use FileOpenPicker class for opening a File dialog
          var openPicker = new FileOpenPicker();
            openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
            openPicker.ViewMode = PickerViewMode.Thumbnail;

             // Filter to include a sample subset of file types.
            openPicker.FileTypeFilter.Clear();
            openPicker.FileTypeFilter.Add("*");
            openPicker.PickMultipleFilesAndContinue();

From above, set the file start location as Desktop, file type as * which will list out all the files and file selection mode as Pick multiple files.
The moment when you select files and click on continue, the request goes to OnActivated event in app.xaml.cs where you need to tweak the code to call the function with respective page as below.

var continuationEventArgs = args as IContinuationActivatedEventArgs;

             if (continuationEventArgs != null)
            {
                var mainPage = rootFrame.Content as MainPage;
                 mainPage.Continue(continuationEventArgs);

            }

Add Continue function in MainPage to retrieve the selected files as below.

public void Continue(IContinuationActivatedEventArgs args)
         {
             if (args.Kind == ActivationKind.PickFileContinuation)
            {
                var openPickerContinuationArgs = args as FileOpenPickerContinuationEventArgs;

                 if (openPickerContinuationArgs.Files.Count > 0)
                {
                    var storageFiles = openPickerContinuationArgs.Files;

                    foreach (var file in storageFiles)
                    {
                        var fileName = file.Name;
                        var displayName = file.DisplayName;
                        var path = file.Path;
                     }
                  }
                 else
                 {
                     // TODO: Write code here to handle picker cancellation.
                }
            }
        }

Download the working sample from below location.
http://nullskull.com/FileUpload/-407123783_FileOperations.zip      






By Siva Jagan Dhulipalla   Popularity  (2204 Views)