Search code examples
c#.netavaloniaui

FileNotFound Exception when deleting existing file


I am making an application with Avalonia UI that can create and delete text files from a UI. I have a bug in my application that after a file is created in the UI if i try to delete the file I get a FileNotFound exception. If i stop and start the application it loads the file and it successfully deletes the file.

I have verified that the text file is present in the output folder (and UI) when the save method is executed,

The file is created here in this method after a button press to "Save"

public void SaveNote()
{
    FileService.SaveToFile(new NoteModel(this.Filename, this.Content));
    OnNoteSaved(this);
}

FileService saves the file like so

public static void SaveToFile(NoteModel note)
{
    if (!Directory.Exists(saveDirectory))
    {
        Directory.CreateDirectory(saveDirectory);
    }
    try
    {
        if(!File.Exists(note.Filename))
        {
            string filepath = Path.Combine(saveDirectory, note.Filename);
            File.WriteAllText(filepath, note.Content);
        }
        else
        {
            File.WriteAllText(note.Filename, note.Content);
        }
    }
    catch (Exception ex)
    {
        throw new Exception($"Error saving file: {note.Filename}\nMessage: {ex.Message}");
    }
}

in a similar way to the save method, the call to delete the file is called here

public void DeleteNote()
{
    FileService.DeleteFile(new NoteModel(this.Filename, this.Content));
    OnNoteDeleted(this);
}

And the delete method in FileService is below

public static void DeleteFile(NoteModel note)
{
    if(Directory.Exists(saveDirectory))
    {
        try
        {
            if(File.Exists(note.Filename))
            {
                File.Delete(note.Filename);
            }
            else
            {
                throw new FileNotFoundException($"File not found: {note.Filename}");
            }
        }
        catch (Exception ex) 
        {
            throw new Exception($"Error deleting file: {note.Filename}\nMessage: {ex.Message}");
        }
    }
    else
    {
        throw new DirectoryNotFoundException($"No Save Directory Found: {saveDirectory}");
    }
}

The exception is thrown in the catch block of DeleteFile shown below. When the application is restarted, the can be successfully deleted

        catch (Exception ex) 
        {
            throw new Exception($"Error deleting file: {note.Filename}\nMessage: {ex.Message}");
        }

Solution

  • It looks like you construct the file path when creating the file, string filepath = Path.Combine(saveDirectory, note.Filename);. However, in your delete method you are passing the file name only.

    You should update your delete method to also create a file path similar to how you did in the create method. Then pass this into the delete method. See here for documentation: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.delete?view=net-8.0