How to access disk in network - vb.net

i have routine for store somes documents into one directory wich run on local drive but get error with network drive if i use path as this "\\172.16.3.145\Directory".
i use this code for create subdirectory needed:
If My.Computer.FileSystem.DirectoryExists(PercorsoDocumenti) = False Then
My.Computer.FileSystem.CreateDirectory(PercorsoDocumenti)
End If
If My.Computer.FileSystem.DirectoryExists(PercorsoOrdini) = False Then
My.Computer.FileSystem.CreateDirectory(PercorsoOrdini)
End If
'+++ creazione della sottodirectory per l'ordine che deve sempre esistere per poter consultare i files presenti +++
If My.Computer.FileSystem.DirectoryExists(PercorsoOrdini & lblIdOrdinePassato.Text) = False Then
My.Computer.FileSystem.CreateDirectory(PercorsoOrdini & lblIdOrdinePassato.Text)
End If
LstViewDocumentiCaricati.Clear()
For Each fileName As String In IO.Directory.GetFiles(PercorsoOrdini & lblIdOrdinePassato.Text)
ImgLstFiles.Images.Add(Icon.ExtractAssociatedIcon(fileName))
LstViewDocumentiCaricati.Items.Add(IO.Path.GetFileName(fileName), ImgLstFiles.Images.Count - 1)
Next
This code work and create directory also in path as "\\server\directory" but get error when i try to list all files in a listview with this other code:
For Each fileName As String In IO.Directory.GetFiles(PercorsoOrdini & lblIdOrdinePassato.Text)
ImgLstFiles.Images.Add(Icon.ExtractAssociatedIcon(fileName))
LstViewDocumentiCaricati.Items.Add(IO.Path.GetFileName(fileName), ImgLstFiles.Images.Count - 1)
Next
The error happen also if i share directory with sufficient permission...it create directory on network drive but go on error when try to list files.
The error are similar to this:
Value of \172.16.3.145\Directory\Docs\document.pdf is not a valid path for filePath
I'm not able to debug in production computer, so i think the error is in listing procedure code because all code firs work (create directory on network drive).
Someone could help me to understand why ?

With code provided in the link How to get the associated icon from a network share file all works perfectly. Tested today with no error or problem. Thanks to all!

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.

Check if file exists in OneDrive via VBA

I'm trying to check if an Excel file exists in OneDrive using Dir(Filename) (without opening it):
strFilePath = "https://d.docs.live.net/ce59asdf4hj34h5k/Folder 1/Folder 2/File.xlsm"
If Dir(strFilePath) <> "" Then
'do something
End If
but Dir(Filename) give me an error: Run-time error '52': Bad filename or number
I tried to do a workaround and check if the URL itself is valid (using the code sample from here) unfortunately the URL is always valid regardless if the file exists or not (if the file in question does not exist One Drive seems to return a default file, at least that's what it does if you test it in a browser, see screenshot below)
Any other ideas on how to solve the problem would be appreciated (I'm trying to do this without actually opening the file since this will create other problems I'm trying to avoid).
Note: I have OneDrive (Sync) installed, but using a local path unfortunately is out of solution's scope. The Soultion has to work with files that are not synced locally.

Macro broke after re-boot - Excel unable to locate external text files

As part of a larger macro Excel retrieves .dat files from a folder. After a crash and rebooting, the macro no longer works and seizes up upon trying to refresh.
There was also changes in security upon reboot where I had to enable all macros to be able to step though this current one.
I have double checked to make sure the path is correct and the files are still there.
Updated code and ended up crashing for unrelated memory issue. Fixed the memory problem and now won't run and is giving the same error code and message as before even with updated code. Current code which will run through the first loop but fails on the second.
If I am not mistaken, Dir just returns the filename found within that directory and not the full path to that file. What likely happened is your directory was initially set to F: so the macro used this as the default path when searching for the file. The best way to do this would be to store your directory in a constant string, and then append the two together. Something like this:
Const fPath as String = "F:YourPathHere\"
strFile = fPath & Dir(fPath & "*.dat")
Debug.Print strFile ' Just to make sure it is setting properly.

UnauthorizedAccessException with File.AppendAllText in VB.NET

I have recently started getting System.UnauthorizedAccessException errors when using File.AppendAllText to write to a shared drive on the network. I think there were some changes to the network when this happened. The code in my application hasn't changed.
I have asked our IT dept to grant me full permission to the folder. I can see I have permissions for Modify, Read & Execute, Read, Write under my username if I navigate to the file and look at the Security tab under properties. I am also part of a group with read, write and modify permissions to the folder.
This works without error in the same folder:
File.WriteAllText(myFile, myText)
This generates a System.UnauthorizedAccessException error when it reaches the AppendallText:
If File.Exists(myFile) = False Then
' Create a file to write to.
Dim createText As String = logTime & " " & report_data
File.WriteAllText(myFile, createText)
Else
Dim appendText As String = logTime & " " & report_data
File.AppendAllText(myFile, appendText)
End If
I have tried deleting the file and creating it again, that made no difference.
I tried File.SetAttributes(myFile, FileAttributes.Normal)
The IT dept can't see what the problem is.
I can manually open, change and modify the file. The problem only arises if I am trying to do this programmatically.
Is there a different 'user' which tries to modify files? Could the file be open somehow, or would that generate a different error?
I'm using VB.NET 2012, .net framework 4.5, Windows 8.1
The network changes were the problem. It doesn't seem possible to resolve this as it is. Instead I made a copy of the text data, append my new text to that, delete the file, and save the updated text to a new file.

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.