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.
Related
I'm trying to automate a document handling process, and I need to check if there are any files inside a certain folder. The process itself removes the files from the folder once it finishes, so I need it to loop back and check if there are any files left.
So far I've been using a sample file like this:
File.Exists("C:\Users\gcaor\Desktop\OC\150.pdf")
150.pdf is the sample file it's searching for, but is there a way to search for any file at all? So that it returns true if there is a file in the folder and false if there isn't
You can use Directory.EnumerateFiles + Any:
Dim anyFileExist = Directory.EnumerateFiles(path).Any()
This is using standard .NET methods and also stops at the first file found.
I found a similar question but it was 5 years 8 months old, had 2 replies and neither worked for me (VB.Net Read txt file from current directory)
My issue is that when I use the following code:
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\Username_And_Password_Raw.txt")
Dim usernameAndPassword = Split(fileReader, ",")
I get an error saying:
System.IO.FileNotFoundException: 'Could not find file 'C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\bin\Debug\net6.0-windows\Username_And_Password_Raw.txt'.'
I have tried using all the different Applications.BLANKPath options I can find (ie; StartupPath, CommonAppDataPath, etc.) and they all return essentially the same error only with a different location.
This is the folder layout of my TXT File - I know it's a terrible, incredibly insecure and generally awful way of storing login information but this is just for a NEA so will never ever actually be used
This is the actual path of the TXT File if it helps
C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\Username_And_Password_Raw.txt
The startup path is where your exe is located. That and all supporting files get copied to a binary directory when you compile in visual studio, in your case
C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\bin\Debug\net6.0-windows
But what you're trying to do, reference the file where it sits in your solution, is probably not the best way to do it, and your code above will work (with a change, will mention later) if you change the properties of the file in the solution.
Right click on the file in the Solution Explorer Username_And_Password_Raw.txt, select Properties. Modify Copy to Output Directory to either Copy always / Copy if newer, depending on your requirement. Now that file will copy to the same directory your exe is in, and the code above should work.
Note, when creating a path, don't use string concatenation because you may have too many or too few \; use Path.Combine:
Dim filePath = Path.Combine(Application.StartupPath, "Username_And_Password_Raw.txt"
Dim fileContents = My.Computer.FileSystem.ReadAllText(filePath)
I encountered the following issue:
When accidentally passing a folder path to the Documents.Open function in VBA Word I get the runtime error 5174 as one would expect.
However all files with names that begin with an underscore get deleted in that moment from that folder.
To replicate:
Assume folder C:/Test/
In said folder have two files:
test.txt
_test.txt
In Word VBA execute the command:
Documents.Open("C:/Test/")
(As part of a subroutine or in the immediate window.)
Result: Runtime Error 5174 and _test.txt is now missing.
Note: Passing a nonexisting file like "C:/Test/abc.txt" or a wrong folder path like "C:/Test" (without the last slash) will not have this effect and won't cause the runtime error.
I have only tested this on one system on a network drive under windows 10 with Microsoft Professional Plus 2019. It's entirely possible that it's an issue with the file system. Does anyone have any suggestions as to why is this happening? I now included the workaround to check if I'm passing a folder, but it's still unnerving.
The Documents.Open method opens the specified document and adds it to the Documents collection. It is designed to take the file path, not a folder. If you want to allow users to pick file(s) you may consider using the file open dialog. The FileOpenDialog triggered by your code which opens a folder for picking files allows specifying file formats that should be supported and visible via the dialog window.
Set dlgSaveAs = Application.FileDialog(msoFileDialogFilePicker)
dlgSaveAs.Filter = "Text Files (.txt)|*.txt|Word Documents (.docx)|*.docx|Word Template (.dotx)|*.dotx|All Files (*.*)|*.*"
dlgSaveAs.ValidateNames = true
Res = dlgSaveAs.Show
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!
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.