Can’t get to files with multiple consecutive spaces at the end of a FOLDER name

  asp.net-mvc, c++, windows

I’m trying to programmaticaly locate a file on a network server where there are multiple directory levels, one of which has two spaces at the end of the name. EG:

MyServerC$TopLevelAccount [email protected]

Note that the Account level represents many folders using account codes for the folder name, and most of them have the two spaces at the end.

I can’t amend the directory structure as it’s used by other processes outside my control. I will know in advance the path down to and including the Account level, so I need to search the Email level subfolders for a file containing an order number in the file name. I also know the order number.

The problem is that FileInfo, Directory and DirectoryInfo all balk at the two spaces. Whilst Windows has allowed the folders to be created, and an automated third party process can create folders and files below the Account level, nothing I have tried so far has worked because the spaces get stripped out by the c# file and directory classes.

I can’t use:

Directory.GetFiles(PathToTopLevel, "*.pdf")

because there are over 1000 Account level folders, each of which might have 5 or 6 Email level folders with possibly many hundreds of pdf files in each one. I did try it but had to kill it when it was still thinking about it after 5 minutes.

Directory.GetFiles(PathToAccountLevel, "*.pdf")  

This returns the ‘can’t find part of the path’ error.

I also tried:

filePath = Path.Combine(PathToAccountLevel, $"{order_no}.pdf");  
var fi = new FileInfo(filePath);

which also returns ‘can’t find part of the path’.

I’ve done lots of trawling through SO and other forums with no success as they are mainly concerned either with file names or single spaces, but I did find a useful method here which I have tried:

filePath = AddQuotesIfRequired(PathToAccountLevel);  
Directory.GetFiles(filePath, "*.pdf")

Which does indeed add the quotes, but it makes no difference to the outcome.

Also tried (with and without adding quotes):

Directory.GetFiles(@filePath, "*.pdf")  

I’ve tried as many combinations as I can think of using quotes and ‘@’ etc. but absolutely nothing has worked so far. I’ve even hard coded the full path down to the Email level and still no joy.

I’m using C# with VS2019 on Windows 10. The server is running Windows Server 2012 R2 DataCenter. I’ve run the test executable locally on the server and the results are the same.

The really galling aspect of this is that a simple test program written in and using FindFirst/Next works perfectly!

I should also mention that permissions are not an issue, and the files exist.

Any help at all would be great, thanks.

Source: Windows Questions

LEAVE A COMMENT