UWP - Сохранение файлов. IOException: процесс не может получить доступ к файлу «путь к файлу», потому что он используется другим процессом - PullRequest
0 голосов
/ 12 января 2020

Я хотел сохранить файл в UWP. Мой фрагмент кода ниже. Это работает иногда. Но иногда терпит неудачу. Не уверен почему? Обычно это происходит, если файл, который нужно сохранить, больше или существует несколько файлов для сохранения.

private async void Download_Click(object sender, RoutedEventArgs e)
    {
        // Clear previous returned file name, if it exists, between iterations of this scenario
        //          TextBlock1.Text = "";

        FileSavePicker savePicker = new FileSavePicker();
        savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
        // Dropdown of file types the user can save the file as
        savePicker.FileTypeChoices.Add("CSV Format", new List<string>() { ".csv" });
        // Default file name if the user does not type one in or select a file to replace
        savePicker.SuggestedFileName = "DataBaseFile1";
        StorageFile file = await savePicker.PickSaveFileAsync();

        using (var stream = await file.OpenStreamForWriteAsync())
        {
            stream.SetLength(0);
            var bytes = Encoding.ASCII.GetBytes("Content");
            await stream.WriteAsync(bytes, 0, bytes.Length);
            await stream.FlushAsync();
        }


        if (file != null)
        {
            // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
            CachedFileManager.DeferUpdates(file);
            // write to file
            //   await FileIO.WriteTextAsync(file, "Example file contents.");

            using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
            {
                await FileIO.WriteTextAsync(file, AllRecordsTitle_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, IDTitle_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, ID_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, FirstNameTitle_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, FirstName_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, LastNameTitle_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, LastName_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, TelNo1Title_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, TelNo1_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, TelNo2Title_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, TelNo2_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, EmailTitle_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, Email_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, AddressTitle_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, Address_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, DetailsTitle_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");
                await FileIO.AppendTextAsync(file, Details_TBlock.Text);
                await FileIO.AppendTextAsync(file, "\n");


            }
            // Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
            // Completing updates may require Windows to ask for user input.
            FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
            if (status == FileUpdateStatus.Complete)
            {
                // TextBlock1.Text = "File " + file.Name + " was saved.";
                var dialog1 = new Windows.UI.Popups.MessageDialog(" File " + file.Name + " was saved. ");
                await dialog1.ShowAsync();
            }
            else if (status == FileUpdateStatus.CompleteAndRenamed)
            {
                // TextBlock1.Text = "File " + file.Name + " was renamed and saved.";
                var dialog2 = new Windows.UI.Popups.MessageDialog(" File " + file.Name + " was renamed and saved. ");
                await dialog2.ShowAsync();
            }
            else
            {
                // TextBlock1.Text = "File " + file.Name + " couldn't be saved.";
                var dialog3 = new Windows.UI.Popups.MessageDialog("File " + file.Name + " couldn't be saved.");
                await dialog3.ShowAsync();
            }
        }
        else
        {
            // TextBlock1.Text = "Operation cancelled.";
            var dialog4 = new Windows.UI.Popups.MessageDialog("Operation cancelled.");
            await dialog4.ShowAsync();
        }


    }   
}
...