Electron.NET: Save Dialog & File Writing

This post is another expansion of my Electron.NET sample to show how to prompt the user with a save dialog and write a file to disk. The sample code before any changes can be found here. As with all the posts I have done on Electron.NET the API Demos repo helped out a lot.

For this example, we will be adding an export button to the contact detail page that will export the contact as JSON.

Dialog Controller

Following how the API Demo is setup I added a DialogController with the following code.

public class DialogsController : Controller
{
    private static bool saveAdded;

    public IActionResult Index()
    {
        if (!HybridSupport.IsElectronActive || saveAdded) return Ok();

        Electron.IpcMain.On("save-dialog", async (args) =>
        {
            var mainWindow = Electron.WindowManager.BrowserWindows.First();
            var options = new SaveDialogOptions
            {
                Title = "Save contact as JSON",
                Filters = new FileFilter[]
                {
                    new FileFilter { Name = "JSON", 
                                     Extensions = new string[] {"json" } }
                }
            };

            var result = await 
                  Electron.Dialog.ShowSaveDialogAsync(mainWindow, options);
            Electron.IpcMain.Send(mainWindow, "save-dialog-reply", result);
        });

        saveAdded = true;

        return Ok();
    }
}

The setup above tells Electron when it receives a save-dialog request to show the operating system’s save dialog with the options specified. When the user completes the dialog interaction then it is set up so Electron will send out a save-dialog-reply message so anything listing can act on the user’s selection.

The bits with saveAdded is to work around an issue I was having with the dialog being shown multiple times. There is something off about my setup that I haven’t had time to track down, but I felt like even with this one querk this post is still valuable.

Next, I added the following import to the _Layout.cshtml file.

<link rel="import" href="Dialogs">

As I am writing this I am wondering if this could be the cause of my multiple dialog issues? Maybe this should just be on the contact detail page?

Contact Detail Page Changes

The rest of the changes are in the Views/Contacts/Details.cshtml. The first thing I did was add a new div and button at the bottom of the page. Based on the look of the existing page it isn’t the prettiest looking thing, but the look of the UI isn’t really the point of this post. Here is the code for the new div. Make note that the button has a specific ID.

<div>
    <button id="save-dialog" class="btn">Export</button>
</div>

Finally, the following script section was added.

<script>
    (function(){
        const { ipcRenderer } = require("electron");
        const fs = require('fs');
        var model = '@Html.Raw(Json.Serialize(@Model))';

        document.getElementById("save-dialog")
                .addEventListener("click", () => {
            ipcRenderer.send("save-dialog");
        });

        ipcRenderer.on("save-dialog-reply", (sender, path) => {
            if (!path) return;

            fs.writeFile(path, model, function (err) {
                console.log(err);
                return;
            });
        });
       
    }());
</script>

On the server side, the model is converted to JSON and stored which will be used when writing the file. If anyone has a better way of doing this part I would love to hear about it in the comments. I’m referring to this bit of code.

var model = '@Html.Raw(Json.Serialize(@Model))';

Next, a click event is added to the export button which when fired sends a message to show the save dialog defined in the controller.

document.getElementById("save-dialog")
        .addEventListener("click", () => {
                                     ipcRenderer.send("save-dialog");
                                   });

Finally, a callback is added for the message that the user has finished with the dialog that was shown.

ipcRenderer.on("save-dialog-reply", (sender, path) => {
    if (!path) return;

    fs.writeFile(path, model, function (err) {
        console.log(err);
        return;
    });
});

In the callback, if the user entered a path then the JSON for the model is written to the selected path.

Wrapping Up

While writing a contact to JSON might not be the most useful thing in the world the same idea could be used to with the information to a vCard file.

After working on this example I finally feel like I am getting a better hold on how Electron is working. Hopefully, this series is helping you feel the same. The completed code can be found here.


Also published on Medium.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.