Jesse Glover
Jesse Glover

Reputation: 335

C# WPF FileSaving Exception encountered

My issue is that I keep seeing a recurring theme with trying to allow my Notepad clone to save a file. Whenever I try to save a file, regardless of the location on the hard disk, the UnauthorizedAccess Exception continues to be thrown. Below is my sample code for what I've done, and I have tried researching this since last night to no avail. Any help would be greatly appreciated.

//located at base class level
private const string fileFilter = "Text Files|*.txt|All Files|*.*";

private string currentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

private void MenuFileSaveAs_Click(object sender, RoutedEventArgs e)
{
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.DefaultExt = "*.txt";
    sfd.Filter = fileFilter;
    sfd.AddExtension = true;
    sfd.InitialDirectory = currentPath;
    sfd.RestoreDirectory = true;
    sfd.OverwritePrompt = true;
    sfd.ShowDialog();

    try
    {
        System.IO.File.WriteAllText(currentPath,TxtBox.Text,Encoding.UTF8);     
    }

    catch (ArgumentException)
    {
        // Do nothing
    }    

    catch(UnauthorizedAccessException)
    {
        MessageBox.Show("Access Denied");
    }
}

Upvotes: 2

Views: 116

Answers (2)

pnm
pnm

Reputation: 148

You need to get the correct path context and file object from the dialog box once the user has hit 'ok'. Namely verify the user actually hit ok and then use the OpenFile property to see what their file selection is:

if (sfd.ShowDialog.HasValue && sfd.ShowDialog)
{
    if (sfd.OpenFile() != null)
    {
        // convert your text to byte and .write()
        sfd.OpenFile.Close();
    }
}

Upvotes: 1

denys-vega
denys-vega

Reputation: 3697

Change the following lines.

...
    if (sfd.ShowDialog() != true)
        return;

    try
    {
        using (var stream = sfd.OpenFile())
        using (var writer = new StreamWriter(stream, Encoding.UTF8))
        {
            writer.Write(TxtBox.Text);
        }
    }
...

I hope it helps you.

Upvotes: 2

Related Questions