Search code examples
c#winforms.net-3.5backup-sqldatabase

C# Win Form - Allow to save file only on LOCAL PC


Brief

I am trying to backup SQL Database through my software. At runtime the software asks the user where does he want the backup to be stored.

Requirement

Now, my requirement is that the user can only create backup on the PC itself or on any pendrive attached to it but not on network PC.

Solution that i came up with

Here is the code i am using:-

SaveFileDialog obj = new SaveFileDialog();
obj.DefaultExt = ".bak";
obj.FileName = FileName;
obj.ShowDialog();
if (obj.FileName != null && obj.FileName != "" && obj.FileName.StartsWith("\\\\") == false)
{
     //Save File Work
}

Question

Now, i want to ask you guys is that will this code obj.FileName.StartsWith("\\\\") == false be sufficient to block the user from saving on network drives or is there any other method i should use to prevent that from happening?


Solution

  • you can check path is network path or not and using new Uri(mypath).IsUnc and then block user based on that

    so code will be like

    if (new Uri(path).IsUnc || IsNetworkPath(path))
    {
      //show message not allowed
      return;
    }
    
    //for checking path is network or not 
    private bool IsNetworkPath(path) 
    {
        FileInfo file = new FileInfo(path);
        DriveInfo drive = new DriveInfo(file.Directory.Root.FullName);
        return dive.DrivType == DrivType .Network;    
    }