0

Is there some method or combination thereof in the .NET API that I can pass a full path i.e. "C:\Directory\File.Ext" to, and check if I can create a file at that location. It would presumably return true or false.

For example,

C:\Directory\file.ext         : true, unless no permission to write there.
C:\Directory\??&#.kc2         : false
asdf                          : false
X:\Directory\file.ext         : false, if no X: drive exists
\\local-pc\directory\file.ext : true
AlphaModder
  • 3,266
  • 2
  • 28
  • 44
  • This seems like a duplicate http://stackoverflow.com/questions/6198392/check-whether-a-path-is-valid – Kat Aug 27 '14 at 19:54
  • 2
    You're looking for [`File.Exists`](http://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx) – Yuval Itzchakov Aug 27 '14 at 19:54
  • And @YuvalItzchakov has a good answer as well if you're looking if you can save there. – Kat Aug 27 '14 at 19:55
  • These kind of tests are worth very little on a multitasking operating system. They do *not* promise that your file operation won't fail. Because a nanosecond after you test, another process can still make the location inaccessible. Leaving you with a serious head-scratcher (I checked, but it still failed!) You can't skip try/catch around the operation, so just don't bother checking up front. – Hans Passant Aug 27 '14 at 20:21
  • Use `try - catch`? This would catch multiple exceptions (e.g., bad path, permissions, etc..) – KSdev Aug 27 '14 at 20:29

1 Answers1

1

Probably the more easier method is to try write to this path (especially UNC paths can be a problem) and try to handle exception if something goes wrong.

Moreover even if you create method which will check permissions, paths, etc. you will have to anyway make exception handler, because something could change between method invocations

Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116