I trying to kill all files with extension xls
Sub testt()
downloadF = Environ("USERPROFILE") & "\Downloads\*.xls"
Kill downloadF
End Sub
But it also kill files .xlsx and .xlsm and everything with .xls*
Why?
How to kill only *.xls?
I have a theory as to why this is happening, but I haven't quite proven it... in the meantime I found an alternate method to delete only the intended files is to refer to the file's "short" (8.3) name:
For example, when I first checked my (NTFS) drive, using the /X switch with Dir at the command prompt:
t.xlsx has a short name of TF99B~1.XLS
...and with Dir /x:
...and programmatically:
Option Explicit
Private Declare Function GetShortPathNameA Lib "kernel32" _
(ByVal lpszLongPath As String, ByVal lpszShortPath As String, ByVal cchBuffer As Long) As Long
Public Function ShortPath(ByVal fName As String) As String
Dim fNum As Integer, strBuffer As String * 255
fNum = FreeFile
If Dir(fName) = "" Then
On Error Resume Next 'Create file if it doesn't exist
Open fName For Output As #fNum
Close #fNum
End If
ShortPath = Left$(strBuffer, GetShortPathNameA(fName, strBuffer, 255))
End Function
As #Pᴇʜ pointed out, if you strip these from the files, eg. with:
fsutil 8dot3name strip c:\temp\test
...the Kill command works as expected (and does not kill xlsx).
fsutil 8dot3name strip : Removes the 8dot3 file names for all files that are located in the specified DirectoryPath. The 8dot3 file name is not removed for any files where the DirectoryPath combined with the file name contains more than 260 characters.
This command lists, but does not modify the registry keys that point to the files that had 8dot3 file names permanently removed.
For more information about the effects of permanently removing the 8dot3 file names from files, see Remarks.
...and through the command line, for a whole folder or volume at once:
To query for the disable 8dot3 name behavior for a disk volume
that is for a specific volume, use:
fsutil 8dot3name query Volume{xyz-VolumeGUID-xyz}
You can also query the 8dot3 name behavior by using the behavior
subcommand.
To remove 8dot3 file names in the D:\MyData directory and all
subdirectories, while writing the information to the log file that is
specified as mylogfile.log, type:
fsutil 8dot3name scan /l mylogfile.log /s d:\MyData
More Info:
Fsutil 8dot3name documentation
Fsutil documentation
Namespaces
'Source: Naming Files, Paths, and Namespaces (Microsoft)
All file systems follow the same general naming conventions for an individual file: a base file name and an optional extension, separated by a period. However, each file system, such as NTFS, CDFS, exFAT, UDFS, FAT, and FAT32, can have specific and differing rules about the formation of the individual components in the path to a directory or file.
. . .
Character count limitations can also be different and can vary depending on the file system and path name prefix format used. This is further complicated by support for backward compatibility mechanisms. For example, the older MS-DOS FAT file system supports a maximum of 8 characters for the base file name and 3 characters for the extension, for a total of 12 characters including the dot separator. This is commonly known as an 8.3 file name. The Windows FAT and NTFS file systems are not limited to 8.3 file names, because they have long file name support, but they still support the 8.3 version of long file names.
\\?\
Win32 File Namespaces
For file I/O, the \\?\ prefix to a path string tells the Windows APIs to disable all string parsing and to send the string that follows it straight to the file system. For example, if the file system supports large paths and file names, you can exceed the MAX_PATH limits that are otherwise enforced by the Windows APIs. For more information about the normal maximum path limitation, see the section Maximum Path Length Limitation.
Because it turns off automatic expansion of the path string, the \\?\ prefix also allows the use of .. and . in the path names, which can be useful if you are attempting to perform operations on a file with these otherwise reserved relative path specifiers as part of the fully qualified path.
Many but not all file I/O APIs support \\?\; you should look at the reference topic for each API to be sure.
\\.\
Win32 Device Namespaces
The \\.\ prefix will access the Win32 device namespace instead of the Win32 file namespace. This is how access to physical disks and volumes is accomplished directly, without going through the file system, if the API supports this type of access. You can access many devices other than disks this way (using the CreateFile and DefineDosDevice functions, for example).
NT Namespaces
There are also APIs that allow the use of the NT namespace convention, but the Windows Object Manager makes that unnecessary in most cases. To illustrate, it is useful to browse the Windows namespaces in the system object browser using the Windows Sysinternals WinObj tool. When you run this tool, what you see is the NT namespace beginning at the root, or \. The subfolder called Global?? is where the Win32 namespace resides.
FAT Naming Convention
Source: Overview of FAT, HPFS, and NTFS File Systems (Microsoft)
FAT uses the traditional 8.3 file naming convention and all filenames must be created with the ASCII character set. The name of a file or directory can be up to eight characters long, then a period . separator, and up to a three character extension. The name must start with either a letter or number and can contain any characters except for the following:
. " / \ [ ] : ; | = ,
If any of these characters are used, unexpected results may occur. The name cannot contain any spaces.
NTFS Naming Conventions
File and directory names can be up to 255 characters long, including any extensions. Names preserve case, but are not case sensitive. NTFS makes no distinction of filenames based on case. Names can contain any characters except for the following:
? " / \ < > * | :
Currently, from the command line, you can only create file names of up to 253 characters.
NOTE: Underlying hardware limitations may impose additional partition size limitations in any file system. Particularly, a boot partition can be only 7.8 GB in size, and there is a 2-terabyte limitation in the partition table.
More Information
MSDN : DeleteFile function
MSDN : DeleteFileFromApp function
MSDN : CheckNameLegalDOS8Dot3 function
Try
Option Explicit
Public Sub DelFiles()
Dim fso As Object, fol As Object, f As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set fol = fso.GetFolder(Environ$("USERPROFILE") & "\Downloads")
For Each f In fol.Files
'Debug.Print f
If fso.GetExtensionName(f) = "xls" Then Kill f
Next f
End Sub
Kill Environ("USERPROFILE") & "\Downloads\*.xls" should kill the .xls only.
However, can you try the following:
Open any folder in Windows
Go to View
Options
View
Uncheck "Hide extensions for known file types"
Click OK
See what is going on
I have no explanation for that, but found something strange.
I created 2 files, one test1.xls and with test2.xlsx. I copied these files to various places:
To %userprofile%\downloads
to %userprofile%\documents
to C:\junk
to U:\junk (where U: is a network share)
to G:\MyDrive\MyDocs\junk (where G: is created by Google File Stream)
For the first three cases (where the files live on C:\), the VBA command dir *.xls and also the Command-prompt dir *.xls listed both files, while for the "foreign" drives, only the test1.xls was listed. I assume that the kill used the same logic.
(Tested on Windows 10)
I have a case where I would like to open a compressed numpy file using mmap mode, but can't seem to find any documentation about how it will work under the covers. For example, will it decompress the archive in memory and then mmap it? Will it decompress on the fly?
The documentation is absent for that configuration.
The short answer, based on looking at the code, is that archiving and compression, whether using np.savez or gzip, is not compatible with accessing files in mmap_mode. It's not just a matter of how it is done, but whether it can be done at all.
Relevant bits in the np.load function
elif isinstance(file, gzip.GzipFile):
fid = seek_gzip_factory(file)
...
if magic.startswith(_ZIP_PREFIX):
# zip-file (assume .npz)
# Transfer file ownership to NpzFile
tmp = own_fid
own_fid = False
return NpzFile(fid, own_fid=tmp)
...
if mmap_mode:
return format.open_memmap(file, mode=mmap_mode)
Look at np.lib.npyio.NpzFile. An npz file is a ZIP archive of .npy files. It loads a dictionary(like) object, and only loads the individual variables (arrays) when you access them (e.g. obj[key]). There's no provision in its code for opening those individual files inmmap_mode`.
It's pretty obvious that a file created with np.savez cannot be accessed as mmap. The ZIP archiving and compression is not the same as the gzip compression addressed earlier in the np.load.
But what of a single array saved with np.save and then gzipped? Note that format.open_memmap is called with file, not fid (which might be a gzip file).
More details on open_memmap in np.lib.npyio.format. Its first test is that file must be a string, not an existing file fid. It ends up delegating the work to np.memmap. I don't see any provision in that function for gzip.
[Question] Does Session::RemoveFiles() remove files in sub directory of source directory? If not, how to implement this ability?
(Please do not ask me why I have the remote directory as /C/testTransfer/. The code just for testing purpose.)
I have a SFTP program using WinSCP .Net assembly. Program language is C++/CLI. It opens up a work file. The file contains many lines of FTP instructions.
One type of instruction I have to handle is to transfer *.txt from source directory. The source directory may contain sub directories which may contain .txt as well. Once transfer is successful, delete the source files.
I use Session::GetFiles() for the transfer. It correctly transfer all .txt files (/C/testTransfer/*.txt), even those in sub directories (/C/testTransfer/sub/*.txt), in the source to the destination.
transferOptions->FileMask = "*.txt";
session->GetFiles("/C/testTransfer", "C:\\temp\\win", false, transferOption);
Now to remove, I use session->RemoveFiles("/C/testTransfer/*.txt"). I only see *.txt in the source (/C/testTransfer/*.txt), but not in the sub directory (/C/testTransfer/sub/*.txt), are removed.
The Session::RemoveFiles can remove even files in subdirectories in general. But not this way with wildcard, because WinSCP will not descend to subdirectories that do not match the wildcard (*.txt). Also note that even if you do not need the wildcard, the Session::RemoveFiles would remove even the subdirectories themselves, what I'm not sure you want it to.
Though you have other (and better = more safe) options:
Use the remove parameter of the Session::GetFiles method to instruct it to remove source file after successful transfer.
If you need to delete source files transactionally (=only after download of all files succeed), iterate the TransferOperationResult::Transfers returned by Session::GetFiles and call the Session::RemoveFiles for each (unless the TransferEventArgs::Error is not null).
Use the TransferEventArgs::FileName to get a file path to pass to the Session::RemoveFiles. Use the RemotePath::EscapeFileMask to escape the file name before passing it to the Session::RemoveFiles.
There's a similar full example available for Moving local files to different location after successful upload.
To recursively delete files matching a wildcard in a standalone operation (not after downloading the same files), use the Session::EnumerateRemoteFiles. Pass your wildcard to its mask argument. Use the EnumerationOptions.AllDirectories option for recursion.
Call the Session::RemoveFiles for each returned file. Use the RemotePath::EscapeFileMask to escape the file name before passing it to the Session::RemoveFiles.
I ran into this problem when uploading a file with a super long name - my database field was only set to 50 characters. Since then, I have increased my database field length, but I'd like to have a way to check the length of the filename before uploading. Below is my code. The validation returns '85' as the character length. And it returns the same count for every different file I upload (none of which have a file name length of 85).
<cfscript>
missing_info = "<p>There was a slight problem with your submission. The following are required or invalid:</p><ul>";
// Check the length of the file name for our database field
if ( len(Form["ResumeFile1"]) gt 100 )
{
missing_info = missing_info & "<li>'Resume File 1' is invalid. Character length must be less than 100. Current count is " & len(Form["ResumeFile1"]) & ".</li>";
validation_error = true;
ResumeFileInvalidMarker = true;
}
</cfscript>
Anyone see anything wrong with this?
Thanks!
http://www.cfquickdocs.com/cf9/#cffile.upload
After you upload the file, the variable "clientFileName" will give you the name of the uploaded file, without a file extension.
The only way to read the filename before you upload it would be to use JavaScript to read and parse the value (file path) in the file field.
A quick clarification in the wording of your question. By the time your code executes the file upload has already happened. The file resides in a temporary directory on the ColdFusion server and the form field related to the file upload contains the temporary filename for that file. Aside from checking to see if a file has been specified, do not do anything directly with that file or you'll be circumventing some built in security.
You want to use the cffile tag with the upload action (or equivalent udf) to move the temp file into a folder of your choosing. At that point you get access to a structure containing lots of information. Usually I "upload" into a temporary directory for the application, which should be outside of the webroot for security.
At this point you'll then want to do any validation against the file, such as filename length, file type, file size, etc and delete the file if it fails any checks. If it passes all checks then you move it into it's final destination which may be inside the webroot.
In your case you'll want to check the cffile structure element clientFile which is the original filename including extension (which you'll need to check, since an extension doesn't need to be present and can be any length).
i know that if 1 is present at the 4th position of binary representation of attribute then this is a directory, but i am not sure if 1 is not present at that location should i consider it as a file?
or is there any other attribute present to determine folder or file ?
please help me.
Thanks.
Every file has a File Record in Master File Table (MFT) of the volume.
You can check the 2-byte flag stored at 0x16 and 0x17(attention, little endian). The second bit (counting from right) tells whether it's a folder(1), or a file(0).
if (flag & 0x02)
it's a folder
else
it's a file
If you change this bit that would originally represent a file to 1 by force, for example with the help of WinHex, and (probably a restart or system cache fresh is needed) double click it, OS would report that the file is corrupted.
In addition, the first bit tells if it is deleted.
if (flag & 0x01)
it's a normal file or folder not deleted
else
it's a deleted file or folder