logo
down
shadow

Perl: Check if string is valid directory, case SENSITIVE


Perl: Check if string is valid directory, case SENSITIVE

By : Ryan
Date : November 18 2020, 01:01 AM
may help you . The only definitive source for the file name is the filesystem itself. This snippet lists the entries in the parent of the target directory and verifies that the name specified matches exactly with one of those entries. I tested in from Linux on a remote NTFS share (mounted with CIFS).
code :
use File::Basename;

$target = shift;
($base,$parent) = fileparse($target);

opendir($PARENT,$parent)
    or die("Error opening '$parent': $!");
%entries = map { $_ => 1 } readdir($PARENT);
closedir($PARENT);

if (-d $target && exists($entries{$base})) {
    print("'$target' exists (and correct case)\n");
} else {
    print("'$target' does not exist.\n");
}


Share : facebook icon twitter icon
In Perl, how can I can check if an encoding specified in a string is valid?

In Perl, how can I can check if an encoding specified in a string is valid?


By : an_anth
Date : March 29 2020, 07:55 AM
seems to work fine You can use the find_encoding function in Encode. Although, if you want to use it as an :encoding layer, you should also check perlio_ok. It's possible (but rare) for an encoding to exist but not support use with :encoding:
code :
use Carp qw(croak);
use Encode qw(find_encoding);

sub run {
    my $args = shift;
    my $enc = find_encoding($args->{encoding}) 
      or croak "$args->{encoding} is not a valid encoding";
    $enc->perlio_ok or croak "$args->{encoding} does not support PerlIO";

    my $is_ok = open my $in,
        sprintf('<:encoding(%s)', $enc->name),
        $args->{input_filename}
    ;
}
Encode::perlio_ok($args->{encoding}) or croak "$args->{encoding} not supported";
Check a string for all or 3 consecutive characters of another string? Regex python NOT case-sensitive

Check a string for all or 3 consecutive characters of another string? Regex python NOT case-sensitive


By : Gary Emilia Pitkis
Date : March 29 2020, 07:55 AM
should help you out Well, problems of this kind (mind bending iteration) tend to have elegant functional solutions:
code :
def not3(string2, string1):
    if len(string2) < 3:  return True    # reaching here, the sequence wasn't found
    if string2[:3] in string1: return False      # test beginning of string2 for existence in string1
    return not3(string2[1:], string1)  # recurse from next char of string2
javascript - check if string is in a array without case sensitive

javascript - check if string is in a array without case sensitive


By : user3785695
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I want to make a filter. Where if you input a word that is in the 'blacklist' it will tell something. I've got all the code but have a problem. , Use indexOf:
code :
if (array.indexOf(input) > -1)
Perl vs SED in terms of doing a case sensitive (yes SENSITIVE) search

Perl vs SED in terms of doing a case sensitive (yes SENSITIVE) search


By : Mandrova
Date : March 29 2020, 07:55 AM
Programmatically check Windows 10's case sensitive directory attribute

Programmatically check Windows 10's case sensitive directory attribute


By : erood
Date : March 29 2020, 07:55 AM
wish of those help Here is my P/Invoke solution thanks to the help of @eryksun's comment.
Edit 2: Added SetDirectoryCaseSensitive()
code :
public static partial class NativeMethods {
    public static readonly IntPtr INVALID_HANDLE = new IntPtr(-1);

    public const FileAttributes FILE_FLAG_BACKUP_SEMANTICS = (FileAttributes) 0x02000000;

    public enum NTSTATUS : uint {
        SUCCESS = 0x00000000,
        NOT_IMPLEMENTED = 0xC0000002,
        INVALID_INFO_CLASS = 0xC0000003,
        INVALID_PARAMETER = 0xC000000D,
        NOT_SUPPORTED = 0xC00000BB,
        DIRECTORY_NOT_EMPTY = 0xC0000101,
    }

    public enum FILE_INFORMATION_CLASS {
        None = 0,
        // Note: If you use the actual enum in here, remember to
        // start the first field at 1. There is nothing at zero.
        FileCaseSensitiveInformation = 71,
    }

    // It's called Flags in FileCaseSensitiveInformation so treat it as flags
    [Flags]
    public enum CASE_SENSITIVITY_FLAGS : uint {
        CaseInsensitiveDirectory = 0x00000000,
        CaseSensitiveDirectory = 0x00000001,
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct IO_STATUS_BLOCK {
        [MarshalAs(UnmanagedType.U4)]
        public NTSTATUS Status;
        public ulong Information;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct FILE_CASE_SENSITIVE_INFORMATION {
        [MarshalAs(UnmanagedType.U4)]
        public CASE_SENSITIVITY_FLAGS Flags;
    }

    // An override, specifically made for FileCaseSensitiveInformation, no IntPtr necessary.
    [DllImport("ntdll.dll")]
    [return: MarshalAs(UnmanagedType.U4)]
    public static extern NTSTATUS NtQueryInformationFile(
        IntPtr FileHandle,
        ref IO_STATUS_BLOCK IoStatusBlock,
        ref FILE_CASE_SENSITIVE_INFORMATION FileInformation,
        int Length,
        FILE_INFORMATION_CLASS FileInformationClass);

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern IntPtr CreateFile(
            [MarshalAs(UnmanagedType.LPTStr)] string filename,
            [MarshalAs(UnmanagedType.U4)] FileAccess access,
            [MarshalAs(UnmanagedType.U4)] FileShare share,
            IntPtr securityAttributes, // optional SECURITY_ATTRIBUTES struct or IntPtr.Zero
            [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
            [MarshalAs(UnmanagedType.U4)] FileAttributes flagsAndAttributes,
            IntPtr templateFile);

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool CloseHandle(
        IntPtr hObject);

    public static bool IsDirectoryCaseSensitive(string directory, bool throwOnError = true) {
        // Read access is NOT required
        IntPtr hFile = CreateFile(directory, 0, FileShare.ReadWrite,
                                    IntPtr.Zero, FileMode.Open,
                                    FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);
        if (hFile == INVALID_HANDLE)
            throw new Win32Exception();
        try {
            IO_STATUS_BLOCK iosb = new IO_STATUS_BLOCK();
            FILE_CASE_SENSITIVE_INFORMATION caseSensitive = new FILE_CASE_SENSITIVE_INFORMATION();
            NTSTATUS status = NtQueryInformationFile(hFile, ref iosb, ref caseSensitive,
                                                        Marshal.SizeOf<FILE_CASE_SENSITIVE_INFORMATION>(),
                                                        FILE_INFORMATION_CLASS.FileCaseSensitiveInformation);
            switch (status) {
            case NTSTATUS.SUCCESS:
                return caseSensitive.Flags.HasFlag(CASE_SENSITIVITY_FLAGS.CaseSensitiveDirectory);

            case NTSTATUS.NOT_IMPLEMENTED:
            case NTSTATUS.NOT_SUPPORTED:
            case NTSTATUS.INVALID_INFO_CLASS:
            case NTSTATUS.INVALID_PARAMETER:
                // Not supported, must be older version of windows.
                // Directory case sensitivity is impossible.
                return false;
            default:
                throw new Exception($"Unknown NTSTATUS: {(uint)status:X8}!");
            }
        }
        finally {
            CloseHandle(hFile);
        }
    }
}
partial class NativeMethods {
    public const FileAccess FILE_WRITE_ATTRIBUTES = (FileAccess) 0x00000100;

    // An override, specifically made for FileCaseSensitiveInformation, no IntPtr necessary.
    [DllImport("ntdll.dll")]
    [return: MarshalAs(UnmanagedType.U4)]
    public static extern NTSTATUS NtSetInformationFile(
        IntPtr FileHandle,
        ref IO_STATUS_BLOCK IoStatusBlock,
        ref FILE_CASE_SENSITIVE_INFORMATION FileInformation,
        int Length,
        FILE_INFORMATION_CLASS FileInformationClass);

    // Require's elevated priviledges
    public static void SetDirectoryCaseSensitive(string directory, bool enable) {
        // FILE_WRITE_ATTRIBUTES access is the only requirement
        IntPtr hFile = CreateFile(directory, FILE_WRITE_ATTRIBUTES, FileShare.ReadWrite,
                                    IntPtr.Zero, FileMode.Open,
                                    FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);
        if (hFile == INVALID_HANDLE)
            throw new Win32Exception();
        try {
            IO_STATUS_BLOCK iosb = new IO_STATUS_BLOCK();
            FILE_CASE_SENSITIVE_INFORMATION caseSensitive = new FILE_CASE_SENSITIVE_INFORMATION();
            if (enable)
                caseSensitive.Flags |= CASE_SENSITIVITY_FLAGS.CaseSensitiveDirectory;
            NTSTATUS status = NtSetInformationFile(hFile, ref iosb, ref caseSensitive,
                                                    Marshal.SizeOf<FILE_CASE_SENSITIVE_INFORMATION>(),
                                                    FILE_INFORMATION_CLASS.FileCaseSensitiveInformation);
            switch (status) {
            case NTSTATUS.SUCCESS:
                return;
            case NTSTATUS.DIRECTORY_NOT_EMPTY:
                throw new IOException($"Directory \"{directory}\" contains matching " +
                                      $"case-insensitive files!");

            case NTSTATUS.NOT_IMPLEMENTED:
            case NTSTATUS.NOT_SUPPORTED:
            case NTSTATUS.INVALID_INFO_CLASS:
            case NTSTATUS.INVALID_PARAMETER:
                // Not supported, must be older version of windows.
                // Directory case sensitivity is impossible.
                throw new NotSupportedException("This version of Windows does not support directory case sensitivity!");
            default:
                throw new Exception($"Unknown NTSTATUS: {(uint)status:X8}!");
            }
        }
        finally {
            CloseHandle(hFile);
        }
    }
}
partial class NativeMethods {
    // Use the same directory so it does not need to be recreated when restarting the program
    private static readonly string TempDirectory =
        Path.Combine(Path.GetTempPath(), "88DEB13C-E516-46C3-97CA-46A8D0DDD8B2");

    private static bool? isSupported;
    public static bool IsDirectoryCaseSensitivitySupported() {
        if (isSupported.HasValue)
            return isSupported.Value;

        // Make sure the directory exists
        if (!Directory.Exists(TempDirectory))
            Directory.CreateDirectory(TempDirectory);

        IntPtr hFile = CreateFile(TempDirectory, 0, FileShare.ReadWrite,
                                IntPtr.Zero, FileMode.Open,
                                FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);
        if (hFile == INVALID_HANDLE)
            throw new Exception("Failed to open file while checking case sensitivity support!");
        try {
            IO_STATUS_BLOCK iosb = new IO_STATUS_BLOCK();
            FILE_CASE_SENSITIVE_INFORMATION caseSensitive = new FILE_CASE_SENSITIVE_INFORMATION();
            // Strangely enough, this doesn't fail on files
            NTSTATUS result = NtQueryInformationFile(hFile, ref iosb, ref caseSensitive,
                                                        Marshal.SizeOf<FILE_CASE_SENSITIVE_INFORMATION>(),
                                                        FILE_INFORMATION_CLASS.FileCaseSensitiveInformation);
            switch (result) {
            case NTSTATUS.SUCCESS:
                return (isSupported = true).Value;
            case NTSTATUS.NOT_IMPLEMENTED:
            case NTSTATUS.INVALID_INFO_CLASS:
            case NTSTATUS.INVALID_PARAMETER:
            case NTSTATUS.NOT_SUPPORTED:
                // Not supported, must be older version of windows.
                // Directory case sensitivity is impossible.
                return (isSupported = false).Value;
            default:
                throw new Exception($"Unknown NTSTATUS {(uint)result:X8} while checking case sensitivity support!");
            }
        }
        finally {
            CloseHandle(hFile);
            try {
                // CHOOSE: If you delete the folder, future calls to this will not be any faster
                // Directory.Delete(TempDirectory);
            }
            catch { }
        }
    }
}
Related Posts Related Posts :
  • How to list the windows tftp server directories and files from command prompt?
  • How should I properly use Git for Visual FoxPro Development?
  • How to create a registry entry with a forward slash in the name
  • Bring Powershell-Console to front from WinForms
  • Add IIS AppPool\ASP.NET v4.0 to local windows group
  • Need a startup script in windows to send ALT+F11 keys?
  • Information about DLL files in windows
  • Prerequisites for learning MFC programming
  • Java Version in a batch file
  • cURL in power shell windows 8.1: "A drive with the name 'localhost' does not exist"
  • How can I make a macro to run a few PowerShell commands one after the other?
  • Add a domain user into a local group when the domain is not available
  • windows 7 bat file leaves out parts of the command
  • psql "more is not recognized" error
  • Bundler error when executing berks command from a rake task on windows
  • Echo first three characters of filenames in CMD Windows
  • yii2 composer.phar update is not working
  • Generate memory dump for a windows service that stops unexpectedly
  • send and receive via Serial port Windows
  • Sending data over ethernet from a Raspberry Pi to a c# program on a windows PC
  • Windows driver installation failure after signing and verifying with signtool using cross signed certificates using SHA-
  • Is there any way to make a First Person Shooter input in Windows 8.1?
  • How to add a program (in this case gmsh) to the PATH
  • Command-line to show a file's properties?
  • ErrorDocument in httpd.conf not working
  • Windows Task Scheduler - specify time window, but only fire once
  • How to delete the mistakenly case-changed renamed tag in github?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org