none
Regex Modification ~ Control input for name validity RRS feed

  • Question

  • Hi there. I have two independent questions.

    a) While coding some lines, I needed a statement like the following: 

    public class Example
    {
        public static void Main()
        {
            string[] getLogicalDrives = Directory.GetLogicalDrives();
    
    
            Regex desiredStrings = new Regex(@"[{0}-{1}", getLogicalDrives[0], getLogicalDrives[getLogicalDrives.Length - 1]);
            //or
            //Regex desiredStrings = new Regex(@"[{0}-{1}, {2}-{3}", getLogicalDrives[0], getLogicalDrives[getLogicalDrives.Length -1],
            //getLogicalDrives[0].ToLwer(), getLogicalDrives[getLogicalDrives.Length -1].ToLower());
    
    
            // . . . . . . . . . . . 
        }
    }

    As you already know, such syntax does not exist. I just needed a suitability like this, but I could not find any such Regex overload in msdn documentation or any other forum.Well, is there or indeed there is not? If not, how would it be possible for doing so? Do you think that I can do it my self by penetrating somewhere in VS C#'s innate classes?

    B) Many times we need to create a directory or/and a file somewhere in disk. By using the Directory.Create(directoryPath) or/and FileCreate(fullFileName) with mistyped directory or/and file name, we get exception as follows:

    

    I could not find any method for controlling if the typed directory/file path is valid.I wanted to use C# Directory and File classes but IsValid() methods etc would not control if the typed string is of the right format. So, I wrote this class, but I cannot optimize it. It works fine, even for strings like C:\cfghjkuuytfgjkliouygfvjhbuhgbjhkugyfcvjhuyhg\fghgbjkuyhbjklijuhybklijuhyjgbjkuhygbjkljuhjbnklljuhbjnkljhvbjmnkfgjkli;gvhbjkuhgfcvbhjkliuh*edcdwcwdcd\fileName.dat


    but I cannot optimize it any further. I also have the sensation that I have overdone it with too many if-statements and not quite clever checking-conditions.Please, evaluate! Thanks!!!!

    using System;
    using System.IO;
    using System.Text.RegularExpressions;
    
    public class ControlFullPathNameValidity
    {
        public static void Main()
        {
            int counter = 0;
            int position = 0;
            char slash = '\\';
            //char[] getInvalidPathChars = Path.GetInvalidPathChars();//I could not make it work
            char[] getInvalidPathChars = { '<', '>', ':', ',', '"', '/', '|', '?', '*', '.', '[', ']', '=' };
            string fullPathFileName = null;
            string[] getLogicalDrives = Directory.GetLogicalDrives();
            string directoryPathSubStr = null, fileNameSubStr = null;
            string yn = null;
            bool tf = true;
    
            Regex fileNameSubStrRegexControl = new Regex(@"^[a-zA-Z]+$");
    
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.Write("Undesired path name characters: ");
            foreach (var item in getInvalidPathChars)
                Console.Write(item + "  ");
            Console.WriteLine();
    
            Console.ForegroundColor = ConsoleColor.Cyan;
    
            do
            {
                while (true)
                {
                    Console.WriteLine("\nPlease, type the desired full path name of the new file: ");
                    fullPathFileName = @Console.ReadLine();
    
                    //Primary checks
                    if (fullPathFileName.Length < 8)
                    {
                        Console.Write("Invalid full name: The full file path name typed\n" +
                                          "contains less than eight characters. Retry (y/n)? ");
                        fullPathFileName = string.Empty;
                        break;
                    }
                    else
                    {
                        for (counter = 0; counter < getLogicalDrives.Length; ++counter)
                            if (fullPathFileName.Remove(1) == getLogicalDrives[counter].Remove(1))
                            {
                                //2nd Test passed.
                                //Console.WriteLine("Hosting Logical Drive: {0}", getLogicalDrives[counter]);
                                counter = 0;
                                break;
                            }
                        if (counter != 0)
                        {
                            Console.Write("Error: The logical directory provided corresponds to\n" +
                                              "no physical directory of this machine. Retry (y/n)? ");
                            break;
                        }
                    }
                    if (!(fullPathFileName.LastIndexOf(@"\") > 1))
                    {
                        Console.Write("Invalid name: The second or/and third character of the full file path\n" +
                                          "are are not of \":\\\" format or no slash exists at all. Retry (y/n)? ");
                        fullPathFileName = string.Empty;
                        break;
                    }
    
                    
                    directoryPathSubStr = fullPathFileName.Remove(fullPathFileName.LastIndexOf(@"\")) + "\\";//Directory path
                    fileNameSubStr = fullPathFileName.Remove(0, fullPathFileName.LastIndexOf(@"\") + 1);//File name                                
                    fullPathFileName = string.Empty;//How do we kill this variable? It is not useful anymore.
    
    
                    //Let us examine the validity of the 1st substring (Directory path)                            
                    if (directoryPathSubStr.Length < 3)
                    {                    
                        Console.Write("Invalid name: The full directory path typed contains\n" +
                                          "less than three characters. Retry (y/n)? ");
                        directoryPathSubStr = fileNameSubStr = string.Empty;
                        break;
                    }
                    else if (!(directoryPathSubStr.Substring(1, 2) == @":\"))
                    {
                        /*OPTIMIZATION: This block won't run at all*/
                        Console.Write("Invalid name: The second or/and third characters of the\n" +
                                      "full file path are not of \":\\\" format. Retry (y/n)? ");
                        directoryPathSubStr = fileNameSubStr = string.Empty;
                        break;
                    }
                    else if(directoryPathSubStr.Length > 3)
                    {
                        /*I cannot optimize this block. I think that 
                         *we can rid of it, but I do not know how.*/
                        if (directoryPathSubStr.Substring(3, 1) == @"\")
                        {
                            Console.Write("*Invalid name: Slash found right\n" +
                                              "after slash. Retry (y/n)? ");
                            directoryPathSubStr = fileNameSubStr = string.Empty;
                            break;
                        }
                    }
    
                    position = directoryPathSubStr.IndexOf(slash, position);
                    //Console.WriteLine("First slash is, as expected, placed in absolute position: {0}", position);
    
                    while (directoryPathSubStr.IndexOf(slash, position + 1) != -1)
                    {
                        /*Sorry. I cannot optimize this while_block any further.
                          I think that it is susceptible of more optimization. 
                          In the future, I will try to start the block with 
                          while(subStr1.IndexOf(slash, position + 1) + 1 < subStr1.Length) */
                        if ((directoryPathSubStr.IndexOf(slash, position + 1) + 1 < directoryPathSubStr.Length) &&
                            (directoryPathSubStr.Substring(directoryPathSubStr.IndexOf(slash, position + 1) + 1, 1) == @"\"))
                        {
                            Console.Write("Invalid name: Slash found right\n" +
                                              "after slash. Retry (y/n)? ");
                            tf = false;
                            break;
                        }
    
                        string currentSubDirectory = directoryPathSubStr.Substring(position + 1, directoryPathSubStr.IndexOf(slash, position + 1) - position - 1);
                        // foreach (var item in getInvalidPathChars) //Not quite proper. I could not find any foreach inside_counter
                        for (int i = 0; i < getInvalidPathChars.Length; ++i)
                        {
                            if (directoryPathSubStr.Substring(position + 1, directoryPathSubStr.IndexOf(slash, position + 1)
                                - position - 1).Contains(getInvalidPathChars[i].ToString()))
                            {
                                Console.Write("Invalid name: Invalid character <{0}> in subdirectory\nstring '{1}'. Retry (y/n)? ", getInvalidPathChars[i],
                                currentSubDirectory, position + directoryPathSubStr.Substring(position + 1, directoryPathSubStr.IndexOf(slash, position + 1)
                                - position - 1).IndexOf(getInvalidPathChars[i].ToString()) + 1);
                                tf = false;
                                break;
                            }
                        }
                        if (!tf)
                            break;
    
                        position = directoryPathSubStr.IndexOf(slash, position + 1);
                    }
    
                    if (!tf)
                        break;
    
                    //Now, let us examine the validity of the 2nd substring 
                    if (fileNameSubStr.Length < 5)
                    {
                        Console.Write("Invalid File Name: the name contains less\n" +
                                          "than five characters. Retry (y/n)? ");
                        break;
                    }
                    else if (!fileNameSubStr.Contains("."))
                    {
                        //Check if the full file name contains no punctuation
                        Console.Write("Invalid File Name: No punctuation in\n" +
                                          "file extension name. Retry (y/n)? ");
                        break;
                    }
                    else if (fileNameSubStr.IndexOf(".") != fileNameSubStr.Length - 4)
                    {
                        //Check if the punctuation is exactly where it is supposed to be (4 positions before end)
                        Console.Write("Invalid File Name: No proper punctuation in the file\n" +
                                          "extension name (i.e. fileName.dat). Retry (y/n)? ");
                        break;
                    }
                    else if (fileNameSubStr.Remove(0, fileNameSubStr.LastIndexOf(".")).Length - 1 != 3)
                    {
                        /*OPTIMIZATION: This block won't run */
                        //Check if the file extension contains exactly 3 characters
                        Console.Write("Invalid File Name: The extension does not strictly\n" +
                                          "contain three letters (a-z or A-Z). Retry (y/n)? ");
                        break;
                    }
                    else if (!fileNameSubStrRegexControl.IsMatch(fileNameSubStr.Remove(0, fileNameSubStr.LastIndexOf(".") + 1)))
                    {
                        /*OPTIMIZATION: This block won't run */
                        //Check if the file extension contains only letters
                        Console.Write("The end of file extension name does contain three characters, but\n" +
                                          "not all of them are strictly letters (a-z or A-Z). Retry (y/n)? ");
                        break;
                    }
                    foreach (var item in getInvalidPathChars)
                        if (fileNameSubStr.Remove(fileNameSubStr.LastIndexOf(".")).Contains(item.ToString()))
                        {
                            Console.Write("Invalid File Name: File name contains at least\n" +
                                              "one invalid character. Retry (y/n)? ");
                            tf = false;
                            break;
                        }
    
                    if (!tf)
                        break;
                    else
                        Console.Write("'{0}' is a valid name.\nWould you like to enter a new file path (y/n)? ", directoryPathSubStr + fileNameSubStr);
    
                    break;
                }
                position = 0;
    
                do
                {
                    yn = @Console.ReadLine();
    
                    switch (yn)
                    {
                        case ("y"):
                            tf = true;
                            break;
                        case ("n"):
                            {
                                Console.WriteLine("Exiting application");
                                break;
                            }
                        default:
                            {
                                Console.Write("Only characters \"y\" or \"n\" allowed. Please, retry.");
                                break;
                            }
                    }
                } while ((yn != "y") && (yn != "n"));
            } while (yn == "y");
    
            Console.ReadLine();
        }
    }


    Tuesday, November 14, 2017 3:23 PM

All replies

  • I'm not really sure I follow all the questions you had. But I'll at least address the invalid path question.

    An invalid path could be invalid for several different reasons.

    1) The string contains invalid characters (as defined by Path.GetInvalidPathChars). All the Path methods are supposed to validate this so you should be able to call any of them and handle exceptions for this case.

    2) The string contains valid characters but is not well formed (i.e. C:\C:\). This is complicated by the fact that the file system determines validness, not .NET so you'd have to at least start with the correct base path otherwise it may follow the wrong rules. For example FAT wouldn't allow more than 256 characters in a file path but NTFS would if you used a \\?\ path. For these types of errors you pretty much have to hit the file system (Directory.Exists or File.Exists, for example).

    3) Lastly, the path may be valid but not exist. This is what the .Exist methods are for.

    In general I would simply use Directory/File.Exists and handle any exceptions. This covers all the cases except a non-existent, but valid path (i.e. Q:\). If you want something that is perhaps a little more reliable then may PathSearchAndQualify from Win32 would work. That function doesn't work with non-rooted paths though I believe. It also wouldn't work with non-DOS paths (i.e. \\.\). But I've never played around with it to find out.

    If you simply want to validate the base drive in a path then use Path.GetPathRoot to get the drive portion. Then use DriveInfo.GetDrives in combination with LINQ to find a matching DriveInfo, if any. It already handles the root formatting for you.


    Michael Taylor http://www.michaeltaylorp3.net

    Tuesday, November 14, 2017 3:58 PM
    Moderator
  • Hello,

    A 100% accurate checking of a path's string format is quite difficult, because different file systems impose different restrictions on filename lengths and the allowed characters within filenames. For windows 10 file system, There are including only 9 illegal characters rather than 13 characters and the full path's length are not specified more than 8 chars.

    And since most file systems today support unicode, one might also need to check for all the rules for correcly encoded unicode, normalization, etc. So we just need to do basically check. There is some information for file path rules in windows.

    And my suggestion is you could use the FileInfo constructor. It will do  some basic checks like "contains invalid characters, path length limits" and so on.

    ArgumentException

    The file name is empty, contains only white spaces, or contains invalid characters.

    PathTooLongException

    The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

    NotSupportedException

    fileName contains a colon (:) in the middle of the string.

    ArgumentNullException

    fileName is null.

    Sincerely,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, November 15, 2017 9:41 AM
    Moderator
  • Michael and Neil  thanx for replying. Look, I have rearranged the question. It is actually two different questions. Alright, I think that FileInfo might be tool I was looking for and it is strange that it was not mentioned in forums as a solution to this issue. 

    Ok, lets us see what is going on with

    char[] getInvalidPathChars = Path.GetInvalidPathChars()

    Now, due to the fact that "A 100% accurate checking of a path's string format is quite difficult, because different file systems impose different restrictions on filename lengths and the allowed characters within filenames. ", if you see at the top of the code, I assigned a kind of manual <getInvalidPathCharacters> command, giving a freedom to a programmer to 'manually' select the desired invalid characters. 

    I will work on FileInfo (and Path I guess) more and I will let you know. Thank you. 



    Wednesday, November 15, 2017 10:53 AM
  • Thank you for replying. Uhh, I think that Directory/File.Exists do not guarantee any such providence or protection. I tried to find methods of those classes, but they did not work. Perhaps they do and it is me not to be in position to handle classes properly. I will check again and I will let you know. I think what that Neil might be the solution to my concern.

    What exactly do you mean by "the file system determines validness, not .NET"?

    Thanx.

    Wednesday, November 15, 2017 10:56 AM
  • Well, in this page you mentioned (FileInfo: https://msdn.microsoft.com/en-us/library/system.io.fileinfo.fileinfo.aspx), I see only six member methods. No one of them appear to perform a check if the typed name (in this case it is already provided @"c:\temp\MyTest.txt") is of the correct format. Exactly under the code line

    string path = @"c:\temp\MyTest.txt";


    So, I think that FileInfo class should be supplied with a relative method that should perform such a critical task. Why should there be an exception thrown once it can be easily avoided?

    I will check it more deeply and I will be back. 





    Wednesday, November 15, 2017 11:13 AM
  • Ok, I think that this is a better method than the previous one. It seems less messy and still runs nicely. By changing a few check-block positions and altering some maths, I was able to do some control eliminations. Have a look please!

    using System; using System.IO; using System.Text.RegularExpressions; public class ControlFullPathNameValidity { public static void Main() { int counter = 0; int position = 0; char slash = '\\'; //char[] getInvalidPathChars = Path.GetInvalidPathChars();//I could not make it work char[] getInvalidPathChars = { '<', '>', ':', ',', '"', '/', '|', '?', '*', '.', '[', ']', '=' }; string fullPathFileName = string.Empty; string[] getLogicalDrives = Directory.GetLogicalDrives(); string directoryPathSubStr = string.Empty, fileNameSubStr = string.Empty; string yn = string.Empty; bool tf = true; foreach (var item in getInvalidPathChars) Console.Write(item + " "); Regex fileNameSubStrRegexControl = new Regex(@"^[a-zA-Z]+$"); Console.ForegroundColor = ConsoleColor.DarkRed; Console.Write("Undesired path name characters: "); foreach (var item in getInvalidPathChars) Console.Write(item + " "); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Cyan; do { while (true) { Console.WriteLine("\nPlease, type the desired full path name of the new file: "); fullPathFileName = @Console.ReadLine(); //Primary checks if (fullPathFileName.Length < 8) { //1st Test Passed Console.Write("Invalid full name: The full file path name typed\n" + "contains less than eight characters. Retry (y/n)? "); fullPathFileName = string.Empty; break; } else { for (counter = 0; counter < getLogicalDrives.Length; ++counter) if (fullPathFileName.Remove(1) == getLogicalDrives[counter].Remove(1)) { //2nd Test passed. //Console.WriteLine("Hosting Logical Drive: {0}", getLogicalDrives[counter]); counter = 0; break; } if (counter != 0) { Console.Write("Error: The logical directory provided corresponds to\n" + "no physical disk drive of this machine. Retry (y/n)? "); fullPathFileName = string.Empty; break; } } if (!fullPathFileName.Contains(@"\")) { Console.Write("Invalid name: Full name contains no slash at all. Retry (y/n)? "); fullPathFileName = string.Empty; break; } else if (fullPathFileName.Substring(1, 2) != @":\") { Console.Write("Invalid name: The second or/and third characters of the\n" + "full file path are not of \":\\\" format. Retry (y/n)? "); fullPathFileName = string.Empty; break; } else if (fullPathFileName.Substring(4, 1) == @"\") { Console.WriteLine("*Invalid name: Slash found right\n" + "after slash. Retry (y/n)? "); fullPathFileName = string.Empty; break; } //Let us break the fullPathFileName into two substrings directoryPathSubStr = fullPathFileName.Remove(fullPathFileName.LastIndexOf(@"\")) + "\\";//Directory path fileNameSubStr = fullPathFileName.Remove(0, fullPathFileName.LastIndexOf(@"\") + 1);//File name fullPathFileName = string.Empty;//How do we kill this variable? It is not useful anymore. //Let us examine the validity of the 1st substring (Directory path) position = 2; while (directoryPathSubStr.IndexOf(slash, position + 1) != -1) { /*Sorry. I cannot optimize this while_block any further. I think that it is susceptible of more optimization. In the future, I will try to start the block with while(subStr1.IndexOf(slash, position + 1) + 1 < subStr1.Length) */ if (directoryPathSubStr.Substring(directoryPathSubStr.IndexOf(slash, position + 1) - 1, 1) == @"\") { Console.Write("Invalid name: Slash found right\n" + "after slash. Retry (y/n)? "); tf = false; break; } string currentSubDirectory = directoryPathSubStr.Substring(position + 1, directoryPathSubStr.IndexOf(slash, position + 1) - position - 1); // foreach (var item in getInvalidPathChars) //Not quite proper. I could not find any foreach inside_counter for (int i = 0; i < getInvalidPathChars.Length; ++i) { if (directoryPathSubStr.Substring(position + 1, directoryPathSubStr.IndexOf(slash, position + 1) - position - 1).Contains(getInvalidPathChars[i].ToString())) { Console.Write("Invalid name: Invalid character <{0}> in subdirectory\nstring '{1}'. Retry (y/n)? ", getInvalidPathChars[i], currentSubDirectory, position + directoryPathSubStr.Substring(position + 1, directoryPathSubStr.IndexOf(slash, position + 1) - position - 1).IndexOf(getInvalidPathChars[i].ToString()) + 1); tf = false; break; } } if (!tf) break; position = directoryPathSubStr.IndexOf(slash, position + 1); } if (!tf) break; //Now, let us examine the validity of the 2nd substring /*if (fileNameSubStr.Length < 5) {

    //This block cannot run!

    Console.Write("Invalid File Name: the name contains less\n" + "than five characters. Retry (y/n)? "); break; } else*/ if (!fileNameSubStr.Contains(".")) { //Check if the full file name contains no punctuation Console.Write("Invalid File Name: No punctuation in\n" + "file extension name. Retry (y/n)? "); break; } else if (fileNameSubStr.IndexOf(".") != fileNameSubStr.Length - 4) { //Check if the punctuation is exactly where it is supposed to be (4 positions before end) Console.Write("Invalid File Name: No proper punctuation in the file\n" + "extension name (i.e. fileName.dat). Retry (y/n)? "); break; } else if (fileNameSubStr.Remove(0, fileNameSubStr.LastIndexOf(".")).Length - 1 != 3) { /*OPTIMIZATION: This block won't run */ //Check if the file extension contains exactly 3 characters Console.Write("Invalid File Name: The extension does not strictly\n" + "contain three letters (a-z or A-Z). Retry (y/n)? "); break; } else if (!fileNameSubStrRegexControl.IsMatch(fileNameSubStr.Remove(0, fileNameSubStr.LastIndexOf(".") + 1))) { /*OPTIMIZATION: This block won't run */ //Check if the file extension contains only letters Console.Write("The end of file extension name does contain three characters, but\n" + "not all of them are strictly letters (a-z or A-Z). Retry (y/n)? "); break; } foreach (var item in getInvalidPathChars) if (fileNameSubStr.Remove(fileNameSubStr.LastIndexOf(".")).Contains(item.ToString())) { Console.Write("Invalid File Name: File name contains at least\n" + "one invalid character. Retry (y/n)? "); tf = false; break; } if (!tf) break; else Console.Write("'{0}' is a valid name.\nWould you like to enter a new file path (y/n)? ", directoryPathSubStr + fileNameSubStr); break; } directoryPathSubStr = fileNameSubStr = string.Empty; position = 0; do { yn = @Console.ReadLine(); switch (yn) { case ("y"): tf = true; break; case ("n"): { Console.WriteLine("Exiting application"); break; } default: { Console.Write("Only characters \"y\" or \"n\" allowed. Please, retry."); break; } } } while ((yn != "y") && (yn != "n")); } while (yn == "y"); Console.ReadLine(); } }




    Wednesday, November 15, 2017 3:13 PM
  • Hello George,

    >>And my suggestion is you could use the FileInfo constructor. It will do  some basic checks like "contains invalid characters, path length limits" and so on.

    What I mean is you could use "try catch" statement to do a basic checking. of course you don't take care some exception like unauthorized or security. It usually throws after fileName checking. As far as I know,

    .Net doesn't provide a perfect methods to check the fileName based on the various file system. And I think your code have implemented  the basic inspection of filename feature.

    Sincerely,

    Fei Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, November 16, 2017 10:58 AM
    Moderator
  • Fei, Thank you for replying. 

    I went through FileInfo and I found this, as you may see in the photo. I then checked the file text.dat and indeed there were data written inside. I do not know how or why the four consequent slashes were allowed. 


    The main idea is to avoid throw exception. I read somewhere that try{} catch{} may also rise when voltage failures occur, you know, if a bit does not arrive properly for example from memory or from disk to CPU due to dust or momentary voltage failure or bit failure for any other reason. This renders try/catch an extremely useful and necessary tool, capable to tackle really unexpected bit transmission failures, out of the programmer's potentials and responsibility to forecast.

    With respect to 'unauthorized' or 'security' checks. I did not embedded any such code because C# provides such controls and, you know, it is supposed for those methods to be used after the basic check I concerned about. Well, look, if you like this snippet, I gift it for free, take it for free! Embed it to C# language if you like and that is all.

    Make a File/Directory/FullFile/WhatEverYouLikeName.IsValid(fileName) method that returns a 'true'or a 'false' and that is all.

    Thank you.

    Cheers.


    Thursday, November 16, 2017 11:45 AM
  • Hello George,

    >>I do not know how or why the four consequent slashes were allowed.

    It seems that .Net Framework has so some job with file name separator. When you copy the real file path the compiler will failed to pass because of escape character '\'. I suggest you should do some checks before you pass argument to fileinfo class.

    The following is a simple demo that indicates how to make use of these exceptions.

    string path = "D:://////////Test12312\\\\TTTTT.txt";
                try
                {
                    Console.WriteLine("The file path is: "+"\n"+path);
    
                    FileInfo fileInfo = new FileInfo(path);
                   string s= fileInfo.FullName;
                }
                catch (Exception e) {
                    if (e is UnauthorizedAccessException)
                    {
                        Console.WriteLine("unauthorized");
                    }
                    else if (e is ArgumentException)
                    {
                        Console.WriteLine("The file name is empty, contains only white spaces, or contains invalid characters.");
                    }
                    else if (e is NotSupportedException) {
                        Console.WriteLine("fileName contains a colon (:) in the middle of the string.");
                    }
    
                    //... Other exception 
                }
    

    Sincerely,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, November 17, 2017 10:43 AM
    Moderator
  • That it a great tool, not mentioned in the forums I happened to see. Just for the records, when D\directory\t.txt typed, no directory is created, in contrast to D:\directory\t.txt (directory and file are created). One has to use an extra if-statement in catch block (if 2nd letter is not ":", then do something).

    Cheers!


    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
            string path = "";
    
            for (int i = 0; i < 2; ++i)
            {
                try
                    {
                    Console.WriteLine("Enter the full path file name: ");
                        path = @Console.ReadLine();
                        Console.WriteLine("The file path is: " + "\n" + path);
    
                        FileInfo fileInfo = new FileInfo(path);
                        string s = fileInfo.FullName;
                    }
                    catch (Exception e)
                    {
                        if (e is UnauthorizedAccessException)
                        {
                            Console.WriteLine("unauthorized");
                        }
                        else if (e is ArgumentException)
                        {
                            Console.WriteLine("The file name is empty, contains only white spaces, or contains invalid characters.");
                        }
                        else if (e is NotSupportedException)
                        {
                            Console.WriteLine("fileName contains a colon (:) in the middle of the string.");
                        }
    
                        //... Other exception 
                    }
    
                Console.WriteLine("path: {0}, filepath: {1}", path.Remove(path.LastIndexOf(@"\") + 1), path.Remove(0, path.LastIndexOf(@"\") + 1));
    
                Directory.CreateDirectory(path.Remove(path.LastIndexOf(@"\") + 1));
                File.Create(path).Close();
            }
            Console.ReadLine();
        }
    }
    

    Remove, Copy, LastIndeOf/Any, all these classes, what a great comfort they offer!!! I love them!


    Friday, November 17, 2017 5:09 PM
  • Hello George,

    >>when D\directory\t.txt typed, no directory is created

    If you enter the "D\directory\t.txt", the program will automatically locate it to your bin folder. You will see that your code create a folder under the bin folder of your current project. You also see the the actual fullpath from "fileInfo.FullName" . These are the default setting in .NET if the filepath doesn't contain":".

    Sincerely,

    Fei Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Sunday, November 19, 2017 9:05 AM
    Moderator
  • Hello George,

    Did you have anything to update?  If you already have got the useful solution from there, you could close the thread by marking the useful reply  as answer, This can be beneficial to other community members reading this thread. Thanks a lot.

    Sincerely,
    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Sunday, November 26, 2017 11:53 AM
    Moderator