Unable to Save Edited DOCX File in MAUI App

George Phillips 20 Reputation points
2025-01-20T14:42:03.38+00:00

When using the OpenFile() method to open Word documents from a file path such as "content://com.app.fileapp.fileprovider/doc_files/demo_241211113315.docx," I am able to edit the document but encounter an issue when attempting to save it—I'm only able to save a copy instead of the original file.

MAUI .NET version 8.0.400

Android API Level is 33

Could someone provide guidance on how to resolve this issue?

public async void OpenFile(Enumerables.FileLocation fileType, string filePath)
{
    if (string.IsNullOrEmpty(filePath))
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            Toast.Make("FileName cannot be blank", ToastDuration.Short).Show();
        });
        return;
    }
    filePath = await SaveFileToShared(fileType, filePath, false);
    Java.IO.File file = new Java.IO.File(filePath);
    if (file.Exists())
    {
        try
        {
            // Set file permissions
            file.SetReadable(true, false);
            file.SetWritable(true, false);
            // Get URI for the file
            Uri pathUri = WrapFileWithUri(AndroidApp.Context, file);
            // Extract file extension and MIME type
            string extension = WebKit.MimeTypeMap.GetFileExtensionFromUrl(pathUri.LastPathSegment);
            string mimeType = WebKit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
            // Create intent
            Intent intent = new Intent(fileType == Enumerables.FileLocation.Note && extension.EndsWith("docx") ? Intent.ActionEdit : Intent.ActionView);
            intent.AddFlags(ActivityFlags.GrantReadUriPermission | ActivityFlags.GrantWriteUriPermission | ActivityFlags.GrantPersistableUriPermission);
            // Set intent data and type
            intent.SetDataAndType(pathUri, mimeType);
            // Persist URI permissions if required
            var resolver = AndroidApp.Context.ContentResolver;
            var existingPermissions = resolver.PersistedUriPermissions;
            if (!existingPermissions.Any(p => p.Uri.Equals(pathUri)))
            {
                try
                {
                    resolver.TakePersistableUriPermission(
                        pathUri,
                        ActivityFlags.GrantReadUriPermission | ActivityFlags.GrantWriteUriPermission
                    );
                }
                catch (Java.Lang.SecurityException secEx)
                {
                    ExtendedFunctions.LogToFile($"Failed to persist URI permission: {secEx.Message}");
                }
            }
            // Start the activity
            var activity = Platform.CurrentActivity as AndroidAppActivity;
            activity?.StartActivityForResult(intent, VeriClaimMobile.Infrastructure.Models.Constants.ACTION_OPEN_WORD_REQUEST_CODE);
        }
        catch (ActivityNotFoundException)
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                Toast.Make("No Application Available to open the file", ToastDuration.Short).Show();
            });
        }
        catch (Exception ex)
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                Toast.Make($"Error opening file: {ex.Message}", ToastDuration.Short).Show();
            });
        }
    }
    else
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            Toast.Make("There was a problem saving the file to Shared Storage", ToastDuration.Short).Show();
        });
    }
}
private Uri WrapFileWithUri(Context context, Java.IO.File file)
{
    if (Build.VERSION.SdkInt < (BuildVersionCodes)24)
    {
        return Uri.FromFile(file);
    }
    return AndroidX.Core.Content.FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".fileprovider", file);
}
Word
Word
A family of Microsoft word processing software products for creating web, email, and print documents.
949 questions
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,914 questions
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 48,181 Reputation points Microsoft Vendor
    2025-01-21T06:09:07.7466667+00:00

    Hello,

    Thanks for your prompt feedback.

    This is not actually an issue, but an intentional design by Google.

    Since Android 11, Google needs to provide a URI virtual path through FileProvider instead of the actual path in the file system when reading files for security reasons. Therefore, after you open this resource to an external application through Intent, the external application actually only obtains the content of the file, but does not know its storage location. This is why you need to choose to save it to a new path when saving a file.

    Once you need to provide files to external applications, this situation is unavoidable. Since changing office documents is a very complex requirement and involves document security issues.

    On the Android native platform, if you need to change the document content directly, you need to first implement a document editor in the application to control the save path. On the native platform, this function is usually implemented by the POI library. This is a large library with a capacity of more than 100mb. If your only requirement is to change office documents, integrating a large class library will increase a lot of overhead.

    If you need to integrate native libraries, you can refer to the following official blog.

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.