Protect single file! - vb.net

I'm trying to protect a folder and the files inside it.
I'm able to protect the folder itself, so that if somebody clicks on it he will get a message:
"You don't currently have permission to access this folder!"
But I can still access files in that folder. For example, if somebody knows the name of a file inside the folder he can type D:\ProtectedFolder\pdffile.pdf and he can open the file!
So, my question is:
Can I protect single files inside the folder?
This is the function that I use for folder lock:
Public Function Lock(ByVal folder As
String, ByVal user As String)
Dim FilePath As String = folder
Dim fs As FileSystemSecurity = File.GetAccessControl(FilePath)
fs.AddAccessRule(New FileSystemAccessRule(user,
FileSystemRights.ListDirectory,
AccessControlType.Deny))
fs.AddAccessRule(New FileSystemAccessRule(user,
FileSystemRights.FullControl,
AccessControlType.Deny))
File.SetAccessControl(FilePath, fs)
Return 0
End Function
Thanks!

You will also have to deny FileSystemRights.Read if you want to prevent that. And technically you have to make sure that the files inherited their rights from the folder.

Specify FileShare.None for File.Open. You can see my C# implementation of it here with full source code. Convert it to VB.NET if you'd like.
This is the message you receive when trying to open a file locked by the application:
I think that's what you're after.

Related

How to get DirectoryInfo for a Onedrive folder with VB.net

I have some code that uses System.IO to find files with a given extension. This works fine with regular folders but fails when the files are in Onedrive's local cache.
My assumption is that the problem is to do with the Onedrive cache folder because if the files are moved out of Onedrive and into a local folder e.g. c:\temp, it all works fine.
Dim Folder As New IO.DirectoryInfo(TextBox_RootFolder.Text)
Filelist = Folder.GetFiles("*.xlsx", IO.SearchOption.AllDirectories)
This is VB, so I believe there should not be any issues with string literals, so I'm stumped.
The path string comes out as something similar to: "C:\Users\user\OneDrive - ThisPlace\MyFolder" so there's nothing particularly weird about the string.
When presented with a folder on Onedrive, my variable 'Folder' is correctly assigned with the full path but an exception is thrown on calling Folder.Getfiles. This results in the error "The tag present in the reparse point buffer is invalid".
BTW, I'm a novice so example code would be really appreciated as a detailed technical explanation is likely to go whoosh over my head.
I'm please to report that I found an easy way to solve the problem.
Firstly I retained the code that uses Folder.Getfiles to provide a list of files as this is fast, elegant and retrieves files in sub-folders.
It still throws an exception when it encounters a cloud sync folder such as Onedrive, DropBox etc., so in the catch I use the Dir() function to loop through the files as this does not have problems with folders of this type.
Here is some pseudo-code to show an example:
Dim sFile As String
sFile = Dir(sPath + "\*.xlsx")
Do While sFile <> ""
[ do stuff here ]
sFile = Dir() '' Get the next file
Loop
I hope this is helpful to someone.

Showing the File Extensions inside the folder

Currently, I am working on a feature that will make the files inside the folder that will not hide the file extensions using this code.
Imports Microsoft.Win32
Sub SetNoDrives(value As Integer, path as string)
Dim RegPath As String = "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]"
Using Key As RegistryKey = Registry.LocalMachine.OpenSubKey(RegPath)
Key.SetValue("HideFileExt", value, RegistryValueKind.DWord)
End Using
End Sub
the problem is, I don't know where to place the string path (folder path) on the code. the path is the specific location where you will always show the file extensions of the files inside the folder.
Any help will be much appreciated.
The reason you don't know where to put the folder path is because there is nowhere to put the folder path. This is a user-wide option, i.e. either extensions are displayed in every folder or no folder for the current user. You don't get to choose on a folder by folder basis. At least, there is no option in Windows/File Explorer to do that and I've never seen mention of it being possible, even when specifically searching for it.

Grabbing current user.config path (Visual Basic)

Is there a way of grabbing the location of the My.Settings user.config location? So for example I want to be able in VB to grab the path of the user.cofing file path to a string
The reason I ask is that I have an application where the user.config file is backed up and then restored, the issue is that with the my.settings folder structure it uses a unique hash with the folder name meaning that I cannot write into the code a static folder path, instead I need to be able to grab the location of the user.config OR be able to get the folder name of the application AppData.
Any ideas?
To put this in perspective, currently I'm using something like this:
Dim filePath As String
filePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) & "\My_App\My_App.exe_Url_<the_hash_that_changes_causing_issues>\1.0.0.0\user.config"
Because of the hash change this will not always work
Try executing this code:
Dim mainConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Dim userConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming)
Dim userLocalConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal)
Console.WriteLine(mainConfig.FilePath)
Console.WriteLine(userConfig.FilePath)
Console.WriteLine(userLocalConfig.FilePath)
You'll need to reference System.Configuration.dll and import System.Configuration.

Opening a file using impersonation

I have been searching the web looking for a way to open a WORD file from a secure network folder by impersonating a user who has access. The closest I've come to finding the answer was this from 2 years ago:
Impersonating in .net (C#) & opening a file via Process.start
Here is the code that I am using. When I set the arguments = LocalFile_Test, everything works perfectly because the user is accessing the local c:\ that is has access to. But when I set arguments = RemoteFile_Test, Word opens up a blank document which is the same effect as if I put garbage in the arguments. So it appears that it cannot find the file even though when I login with the user/domain/password that I specify in the properties below, I can find that exact file name and it is not empty. Does anything jump out at you right away? I appreciate your time.
Dim LocalFile_Test As String = "C:\New.docx"
Dim RemoteFile_Test As String = "\\Server1\Apps\File\New.docx"
Dim MyStartInfo As New System.Diagnostics.ProcessStartInfo
MyStartInfo.FileName = "C:\Program Files\Microsoft Office\Office12\WINWORD.exe "
MyStartInfo.Arguments = LocalFile_Test
MyStartInfo.LoadUserProfile = True
MyStartInfo.UseShellExecute = False
MyStartInfo.UserName = "specialuser"
MyStartInfo.Domain = "mydomainname"
MyStartInfo.Password = New System.Security.SecureString()
MyStartInfo.Password.AppendChar("p"c)
MyStartInfo.Password.AppendChar("a"c)
MyStartInfo.Password.AppendChar("s"c)
MyStartInfo.Password.AppendChar("s"c)
Process.Start(MyStartInfo)
My understanding is that you are trying to get a password protected file from a server, and when you do process start, it just opens up a blank word doc. I think the error is how you are trying to get the file, I think you have to map the actual physical path of the file on the server, like
System.Web.HttpContext.Current.Server.MapPath("\\Server1\Apps\File\New.docx")
From there, I am fairly certain, you need to create network credentials for the user like
System.Net.NetworkCredential=New NetworkCredential(userName:=, password:=)
Finally, once that is done, you can either write the file, or transmit the file like so...
System.Web.HttpContext.Current.Response.TransmitFile(file name)
System.Web.HttpContext.Current.Response.WriteFile(file name)
Then,once you get the file, you can try to open it with process start.
Hope that helps, let me know if what I said doesn't work.

Capture only the file path from the file upload control

I am trying to update some local access databases from a web database. When I am accessing the web page, I want the user to select a folder on the local hard drive where the DB's reside that will be updated by the program. I actually have been using the File Upload control to do this as it has allowed me to check the file extensions on the local DB's their file size and other misc. items.
This captures the full path with the file name...
fileName = FileUploadAccess.PostedFile.FileName.ToLower
Now I have a need to capture the full path of the db's on the local hard drive. I can get the full path with the filename, but then I need to write a bunch of code to strip the filename from the path variable.
Is there a simple way to capture the path of the location the DB when the file location is selected, something like this....
Dim thePath As String = System.IO.Path.GetFullPath
Thanks for any suggestions.
You can use IO.Path.GetDirectoryName
Here is a sample code:
Dim MyDirectoryPath As String = System.IO.Path.GetDirectoryName(MyFullPath)