The following class is a wrapper for Microsoft.Win32.SaveFileDialog
. I've implemented the usage of Microsoft.Win32.SaveFileDialog
this way because I'm using the ISaveFileDialog
interface as a dependency throughout my code base.
public class SaveFileDialog : ISaveFileDialog
{
public bool Save(string content, string suggestedFileExtension = null, string suggestedFileExtensionName = null, string suggestedFileName = null)
{
string filter = "All Files|*.*";
if (suggestedFileExtension != null)
{
filter = $"{suggestedFileExtensionName ?? string.Empty}|*{suggestedFileExtension}|" + filter;
}
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog
{
FileName = suggestedFileName ?? string.Empty,
DefaultExt = suggestedFileExtension ?? string.Empty,
Filter = filter
};
switch (dlg.ShowDialog())
{
case true:
return WriteFile(dlg.FileName, content);
default:
return false;
}
}
private bool WriteFile(string filePath, string content)
{
try
{
File.WriteAllText(filePath, content);
return true;
}
catch (PathTooLongException)
{
return false;
}
catch (DirectoryNotFoundException)
{
return false;
}
catch (IOException)
{
return false;
}
catch (UnauthorizedAccessException)
{
return false;
}
catch (System.Security.SecurityException)
{
return false;
}
}
}
While this works, I'm struggling to refactor this class to allow for unit testing as currently there's no way to mock/stub the Microsoft.Win32.SaveFileDialog
- have I missed a trick here? Or is there genuinely no nice way to unit test this and I should be relying on integration tests?
I know that I could refactor the catch blocks to either be
catch (Exception)
{
return false;
}
Or even to be
catch (Exception ex) when (ex is PathTooLongException
|| ex is DirectoryNotFoundException
........ )
{
return false;
}
But I would like to keep them the way that they are because I would like to avoid catching all exceptions and I'm using a Visual Studio plugin to help me manage exceptions and it complains when using the second option.
Thanks for any help!