Illegal Char error after illegal char's are removed.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Fuzz13
    New Member
    • Jun 2010
    • 110

    #1

    Illegal Char error after illegal char's are removed.

    I'm writing a program that a user loads a file (txt or csv) in which it reads newlines and commas as new object delimiters. Each new object is put into an array creating a new array object each time. There is also several tests in place to check the data being read into the program to return an error if there are characters that can't be used for a file or folder. There is an option to clean the data being read in which it will read a line of data, then run several replace statements on it to change illegal characters for safe characters. Somewhere in my code it is cleaning the data, replacing the illegal characters then trying to create files off the array objects but even though I've cleaned the data of illegal characters, upon creation, visual studio is spitting out its own error saying illegal characters (not the error I built as a test). Any ideas on why this might be are greatly appreciated. Bellow is the code in question.

    Code:
     private void Runbtn_Click(object sender, EventArgs e)
           
            {//1
                string[] lines = null; //create lines array
    
                using (StreamReader sr = new StreamReader(@newobject.csvDirectory))
                {//2
                    string fileContents = sr.ReadToEnd();
                    lines = fileContents.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                }//2
    
                bool safeLength = true;
    
                if (Filebtn.Checked == true)
                {//3                
    
                    for (int i = 0; i < lines.Length; i++)
                    {//4
                        if (lines[i].Length > MAXFILENAME)
                        {//5
                            newobject.fileNameError();
                            safeLength = false;
                            break;
                        }//5
    
                    }//4
    
                    if (safeLength == true)
                    {//4
    
                        if (cleancheckbox.Checked == true)
                        { //5                                                           
                            newobject.creationInProgress(); // prompts that files are being made                    
    
                            //create the child form
                            newobject.ParentFolder = newfldrbx.Text;
    
                            // Specify a folder to house everything new inside
                            //This is not the folder that holds the created files/folders
                            // based off of csv/txt values
                            string outputdir = folderBrowserDialog1.SelectedPath;
    
                            //Create a new subfolder under the current active folder
                            // this new folder will hold all files/folders created
                            // per project.
                            string newPath = System.IO.Path.Combine(outputdir, newobject.ParentFolder);
    
                            // Create the subfolder
                            System.IO.Directory.CreateDirectory(newPath);
    
                            for (int i = 0; i < lines.Length; i++)
                            {//6
                                lines[i] = newobject.cleanText(lines[i]); // sends data to get cleaned
    
    
                                //takes the input from the new folder text box
                                // and assigns it to the filename variable
                                string fileName = lines[i] + ".txt";
    
                                // creates new file based off of file name input annd
                                // parent directory
                                string newFile = System.IO.Path.Combine(newPath, fileName);
                                System.IO.File.Create(@newFile);
                            }//6
                        }//5
    
                        else if (cleancheckbox.Checked == false)
                        {
    
                            // Return an error for file with illegal characters
    
                            bool linesOK = true;
                            for (int i = 0; i < lines.Length; i++)
                            {
                                if (lines[i].IndexOfAny(illegal) != -1)
                                {
                                    newobject.illegalError();
                                    linesOK = false;
                                    break;
                                }
                            }
    
                            if (linesOK == true)
                            {
                                newobject.creationInProgress();
    
                                for (int i = 0; i < lines.Length; i++)
                                {
                                    // stores the string entered for the new folder name
                                    newobject.ParentFolder = newfldrbx.Text;
    
                                    // Specify a folder to house everything new inside
                                    //This is not the folder that holds the created files/folders
                                    // based off of csv/txt values
                                    string outputdir = folderBrowserDialog1.SelectedPath;
    
                                    //Create a new subfolder under the current active folder
                                    // this new folder will hold all files/folders created
                                    // per project.
                                    string newPath = System.IO.Path.Combine(outputdir, newobject.ParentFolder);
    
                                    // Create the subfolder
                                    System.IO.Directory.CreateDirectory(newPath);
    
                                    //takes the input from the new folder text box
                                    // and assigns it to the filename variable
                                    string fileName = lines[i] + ".txt";
    
                                    // creates new file based off of file name input annd
                                    // parent directory
                                    string newFile = System.IO.Path.Combine(newPath, fileName);
                                    System.IO.File.Create(@newFile);
                                }
                            }
                        }
                    }
                }
    
    
                else if (folderbtn.Checked == true)
                {
                    if (cleancheckbox.Checked == true)
                    {
                       
    
                        // Get the value to be passed
                        string parentfolder = newfldrbx.Text;
    
                        //create the child form
                        newobject.ParentFolder = parentfolder;
    
                        // Specify a "currently active folder"
                        string outputdir = folderBrowserDialog1.SelectedPath;
    
                        //Create a new subfolder under the current active folder
                        string newParent = System.IO.Path.Combine(outputdir, newobject.ParentFolder);
    
                        // Create the subfolder
                        System.IO.Directory.CreateDirectory(newParent);
    
    
                        for (int i = 0; i < lines.Length; i++)
                        {
                            lines[i] = newobject.cleanText(lines[i]);
    
                            //Create a new subfolder under the current active folder
                            string newChild = System.IO.Path.Combine(newParent, lines[i]);
    
                            // Create the subfolder
                            System.IO.Directory.CreateDirectory(newChild);
                        }
    
                        newobject.creationInProgress();
                    }
    
                    else if (cleancheckbox.Checked == false)
                    {
    
    
                        // Return an error for file with illegal characters
                        bool linesOK = true;
                        for (int i = 0; i < lines.Length; i++)
                        {
                            if (lines[i].IndexOfAny(illegal) != -1)
                            {
                                newobject.illegalError();
                                linesOK = false;
                                break;
                            }
                        }
    
                        // if the file chosen has no illegal characers this this set of
                        // commmands occurs
                        if (linesOK == true)
                        {
    
                            // Get the value to be passed
                            string parentfolder = newfldrbx.Text;
    
                            //create the child form
                            newobject.ParentFolder = parentfolder;
    
                            // Specify a "currently active folder"
                            string outputdir = folderBrowserDialog1.SelectedPath;
    
                            //Create a new subfolder under the current active folder
                            string newParent = System.IO.Path.Combine(outputdir, newobject.ParentFolder);
    
                            // Create the subfolder
                            System.IO.Directory.CreateDirectory(newParent);
    
                            for (int k = 0; k < lines.Length; k++)
                            {
                                //Create a new subfolder under the current active folder
                                string newChild = System.IO.Path.Combine(newParent, lines[k]);
    
                                // Create the subfolder
                                System.IO.Directory.CreateDirectory(newChild);
    
                            }
                            // this lets the user know the folders were made
                            // and must lie outside of the loops to only iterate
                            // one time
                            newobject.creationInProgress();
    
                        }
                    }
                }
                }
    and here is the replace statement:
    Code:
        public string cleanText(string c)
        {
            string cleanText = c.Replace("/", "-");
            string cleanText2 = cleanText.Replace("\\", "-");
            string cleanText3 = cleanText2.Replace(":", "-");
            string cleanText4 = cleanText3.Replace("?", "-");
            string cleanText5 = cleanText4.Replace("*", "-");
            string cleanText6 = cleanText5.Replace("|", "-");
            string cleanText7 = cleanText6.Replace("\"", "");
            
                
            return cleanText7;
        }
    Thanks for everyones help on this.
  • JKing
    Recognized Expert Top Contributor
    • Jun 2007
    • 1206

    #2
    What is the value of the string newFile?

    Comment

    • Fuzz13
      New Member
      • Jun 2010
      • 110

      #3
      The user types in a text box a name of a folder (this folder is not one that exists but rather one that will be made)
      The name typed in is stored as value "newobject.Pare ntFolder"
      Next the user will browse to an already existing folder from which to work from (i.e. My Documents)
      The directory name of the folder they browsed to is stored as "outputdir"
      The next step is that the program combines the outputdir (directory name of browsed to folder) with the to-be-created folder "parentfold er"
      This combination of "outputdir" and "parentfold er" is then stored as "newPath"
      The program then builds the users new folder (the folder for the given project) in this line of code:
      Code:
      System.IO.Directory.CreateDirectory(newPath);
      Next there is a for loop that will continue for every item within the given array (the array's length is determined earlier in the code when the file selected is read in line by line)

      Then I have each object in the array add the extension ".txt" here:
      Code:
      string fileName = lines[i] + ".txt";
      as you can see the new "object[i].txt"
      is stored as "fileName" (fileName is reassigned with each iteration of the for loop to accommodate the next object of the array.
      This shouldn't be an issue as the file is being created before restarting the beginning of the for loop and reassigning the value "fileName")

      Finally there is the newFile value you asked about.
      "newFile" is stored as a combination of "newPath" (i.e. combination of "outputdir" and "parentfold er") and "fileName" (i.e. object[i].txt)

      So for each "newFile" it should be creating either a file or a folder (based off a selection within the program)
      the file/folder will be named based off the name of the currently read object of the array, and created inside the folder name
      the user types in to create (a folder not in existence) and that folder will be created within a selected directory (i.e. My Documents)

      That was a very long answer to your question but I think it was necessary since newFile is based off a lot of other combinations.

      Thanks for your help.

      Comment

      • JKing
        Recognized Expert Top Contributor
        • Jun 2007
        • 1206

        #4
        That still doesn't answer my question. I understand your logic in building the string newFile based off user-input and other variables. That is all fine and dandy but I want to know the value of the string before the error occurs. I am assuming the error is occurring on one of the following lines:
        Code:
        System.IO.File.Create(@newFile);
        If this is the case I want to know the value of newFile when the error occurred. This will help hint as to what is going on.

        Comment

        • Fuzz13
          New Member
          • Jun 2010
          • 110

          #5
          Ah. I totally misunderstood. The file being loaded appears as such:
          Code:
          first line is safe
          2nd line has ** illegal char
          third line is safe
          ** oh no
          hello // goodbye
          "try this"
          \and this?
          The weird thing is any line by itself is running fine for example:

          "This sentence needs fixed***"

          the program will either fail my test in place and give an error (one of mine) or if the user chooses to replace illegal characters it will create the file/folder named:

          "This sentence needs fixed---"

          Hope that was the appropriate answer to your question.

          Comment

          • JKing
            Recognized Expert Top Contributor
            • Jun 2007
            • 1206

            #6
            Okay you are missing what I mean.

            Code:
             private void Runbtn_Click(object sender, EventArgs e)
             
                    {//1
                        string[] lines = null; //create lines array
             
                        using (StreamReader sr = new StreamReader(@newobject.csvDirectory))
                        {//2
                            string fileContents = sr.ReadToEnd();
                            lines = fileContents.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        }//2
             
                        bool safeLength = true;
             
                        if (Filebtn.Checked == true)
                        {//3                
             
                            for (int i = 0; i < lines.Length; i++)
                            {//4
                                if (lines[i].Length > MAXFILENAME)
                                {//5
                                    newobject.fileNameError();
                                    safeLength = false;
                                    break;
                                }//5
             
                            }//4
             
                            if (safeLength == true)
                            {//4
             
                                if (cleancheckbox.Checked == true)
                                { //5                                                           
                                    newobject.creationInProgress(); // prompts that files are being made                    
             
                                    //create the child form
                                    newobject.ParentFolder = newfldrbx.Text;
             
                                    // Specify a folder to house everything new inside
                                    //This is not the folder that holds the created files/folders
                                    // based off of csv/txt values
                                    string outputdir = folderBrowserDialog1.SelectedPath;
             
                                    //Create a new subfolder under the current active folder
                                    // this new folder will hold all files/folders created
                                    // per project.
                                    string newPath = System.IO.Path.Combine(outputdir, newobject.ParentFolder);
            						
                                    // Create the subfolder
                                    //System.IO.Directory.CreateDirectory(newPath);
            						MessageBox.Show(newPath);
             
                                    for (int i = 0; i < lines.Length; i++)
                                    {//6
                                        lines[i] = newobject.cleanText(lines[i]); // sends data to get cleaned
             
             
                                        //takes the input from the new folder text box
                                        // and assigns it to the filename variable
                                        string fileName = lines[i] + ".txt";
             
                                        // creates new file based off of file name input annd
                                        // parent directory
                                        string newFile = System.IO.Path.Combine(newPath, fileName);
                                        //System.IO.File.Create(@newFile);
            							MessageBox.Show(newFile);
                                    }//6
                                }//5
             
                                else if (cleancheckbox.Checked == false)
                                {
             
                                    // Return an error for file with illegal characters
             
                                    bool linesOK = true;
                                    for (int i = 0; i < lines.Length; i++)
                                    {
                                        if (lines[i].IndexOfAny(illegal) != -1)
                                        {
                                            newobject.illegalError();
                                            linesOK = false;
                                            break;
                                        }
                                    }
             
                                    if (linesOK == true)
                                    {
                                        newobject.creationInProgress();
             
                                        for (int i = 0; i < lines.Length; i++)
                                        {
                                            // stores the string entered for the new folder name
                                            newobject.ParentFolder = newfldrbx.Text;
             
                                            // Specify a folder to house everything new inside
                                            //This is not the folder that holds the created files/folders
                                            // based off of csv/txt values
                                            string outputdir = folderBrowserDialog1.SelectedPath;
             
                                            //Create a new subfolder under the current active folder
                                            // this new folder will hold all files/folders created
                                            // per project.
                                            string newPath = System.IO.Path.Combine(outputdir, newobject.ParentFolder);
             
                                            // Create the subfolder
                                            //System.IO.Directory.CreateDirectory(newPath);
            								MessageBox.Show(newPath);
             
                                            //takes the input from the new folder text box
                                            // and assigns it to the filename variable
                                            string fileName = lines[i] + ".txt";
             
                                            // creates new file based off of file name input annd
                                            // parent directory
                                            string newFile = System.IO.Path.Combine(newPath, fileName);
                                            //System.IO.File.Create(@newFile);
            								MessageBox.Show(newFile);
                                        }
                                    }
                                }
                            }
                        }
             
             
                        else if (folderbtn.Checked == true)
                        {
                            if (cleancheckbox.Checked == true)
                            {
             
             
                                // Get the value to be passed
                                string parentfolder = newfldrbx.Text;
             
                                //create the child form
                                newobject.ParentFolder = parentfolder;
             
                                // Specify a "currently active folder"
                                string outputdir = folderBrowserDialog1.SelectedPath;
             
                                //Create a new subfolder under the current active folder
                                string newParent = System.IO.Path.Combine(outputdir, newobject.ParentFolder);
             
                                // Create the subfolder
                                //System.IO.Directory.CreateDirectory(newParent);
            					MessageBox.Show(newParent);
             
             
                                for (int i = 0; i < lines.Length; i++)
                                {
                                    lines[i] = newobject.cleanText(lines[i]);
             
                                    //Create a new subfolder under the current active folder
                                    string newChild = System.IO.Path.Combine(newParent, lines[i]);
             
                                    // Create the subfolder
                                    //System.IO.Directory.CreateDirectory(newChild);
            						MessageBox.Show(newChild);
                                }
             
                                newobject.creationInProgress();
                            }
             
                            else if (cleancheckbox.Checked == false)
                            {
             
             
                                // Return an error for file with illegal characters
                                bool linesOK = true;
                                for (int i = 0; i < lines.Length; i++)
                                {
                                    if (lines[i].IndexOfAny(illegal) != -1)
                                    {
                                        newobject.illegalError();
                                        linesOK = false;
                                        break;
                                    }
                                }
             
                                // if the file chosen has no illegal characers this this set of
                                // commmands occurs
                                if (linesOK == true)
                                {
             
                                    // Get the value to be passed
                                    string parentfolder = newfldrbx.Text;
             
                                    //create the child form
                                    newobject.ParentFolder = parentfolder;
             
                                    // Specify a "currently active folder"
                                    string outputdir = folderBrowserDialog1.SelectedPath;
             
                                    //Create a new subfolder under the current active folder
                                    string newParent = System.IO.Path.Combine(outputdir, newobject.ParentFolder);
             
                                    // Create the subfolder
                                    //System.IO.Directory.CreateDirectory(newParent);
            						MessageBox.Show(newParent);
             
                                    for (int k = 0; k < lines.Length; k++)
                                    {
                                        //Create a new subfolder under the current active folder
                                        string newChild = System.IO.Path.Combine(newParent, lines[k]);
             
                                        // Create the subfolder
                                        //System.IO.Directory.CreateDirectory(newChild);
            							MessageBox.Show(newChild);
             
                                    }
                                    // this lets the user know the folders were made
                                    // and must lie outside of the loops to only iterate
                                    // one time
                                    newobject.creationInProgress();
             
                                }
                            }
                        }
                        }
            Copy your current code and paste it into a text file and save it for a backup.
            Now copy this code paste it in and run your program. Enter some values for the folder names and tell me what the messageboxes say.
            Last edited by JKing; Jul 28 '10, 08:28 PM. Reason: Fixed ending code tag

            Comment

            • JKing
              Recognized Expert Top Contributor
              • Jun 2007
              • 1206

              #7
              What I am trying to get you to see is that your variable newFile and/or newPath may not contain the data that you think they do...

              I don't have access to VS at the moment but I am fairly certain that the file dialog selected path returns the path with a \ at the end. Use that with the Path.Combine method and you now have a \\ in your string. The @ symbol on newFile says to take it literally and this will give you your illegal character error.

              Comment

              • Fuzz13
                New Member
                • Jun 2010
                • 110

                #8
                I'm getting the same error as before: Illegal character

                Here's the details:
                See the end of this message for details on invoking
                just-in-time (JIT) debugging instead of this dialog box.

                ************** Exception Text **************
                System.Argument Exception: Illegal characters in path.
                at System.IO.Path. CheckInvalidPat hChars(String path)
                at System.IO.Path. Combine(String path1, String path2)
                at WindowsFormsApp lication1.Form1 .Runbtn_Click(O bject sender, EventArgs e) in C:\Users\Dahlia \Desktop\CSV program\Form1.c s:line 137
                at System.Windows. Forms.Control.O nClick(EventArg s e)
                at System.Windows. Forms.Button.On Click(EventArgs e)
                at System.Windows. Forms.Button.On MouseUp(MouseEv entArgs mevent)
                at System.Windows. Forms.Control.W mMouseUp(Messag e& m, MouseButtons button, Int32 clicks)
                at System.Windows. Forms.Control.W ndProc(Message& m)
                at System.Windows. Forms.ButtonBas e.WndProc(Messa ge& m)
                at System.Windows. Forms.Button.Wn dProc(Message& m)
                at System.Windows. Forms.Control.C ontrolNativeWin dow.OnMessage(M essage& m)
                at System.Windows. Forms.Control.C ontrolNativeWin dow.WndProc(Mes sage& m)
                at System.Windows. Forms.NativeWin dow.Callback(In tPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


                ************** Loaded Assemblies **************
                mscorlib
                Assembly Version: 4.0.0.0
                Win32 Version: 4.0.30319.1 (RTMRel.030319-0100)
                CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
                ----------------------------------------
                WindowsFormsApp lication1
                Assembly Version: 1.0.0.0
                Win32 Version: 1.0.0.0
                CodeBase: file:///C:/Users/Dahlia/Desktop/CSV%20program/WindowsFormsApp lication1/WindowsFormsApp lication1/bin/Release/WindowsFormsApp lication1.exe
                ----------------------------------------
                System.Windows. Forms
                Assembly Version: 4.0.0.0
                Win32 Version: 4.0.30319.1 built by: RTMRel
                CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows. Forms/v4.0_4.0.0.0__b 77a5c561934e089/System.Windows. Forms.dll
                ----------------------------------------
                System.Drawing
                Assembly Version: 4.0.0.0
                Win32 Version: 4.0.30319.1 built by: RTMRel
                CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b 03f5f7f11d50a3a/System.Drawing. dll
                ----------------------------------------
                System
                Assembly Version: 4.0.0.0
                Win32 Version: 4.0.30319.1 built by: RTMRel
                CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b 77a5c561934e089/System.dll
                ----------------------------------------
                System.Xml
                Assembly Version: 4.0.0.0
                Win32 Version: 4.0.30319.1 built by: RTMRel
                CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b 77a5c561934e089/System.Xml.dll
                ----------------------------------------

                ************** JIT Debugging **************
                To enable just-in-time (JIT) debugging, the .config file for this
                application or computer (machine.config ) must have the
                jitDebugging value set in the system.windows. forms section.
                The application must also be compiled with debugging
                enabled.

                For example:

                <configuratio n>
                <system.windows .forms jitDebugging="t rue" />
                </configuration>

                When JIT debugging is enabled, any unhandled exception
                will be sent to the JIT debugger registered on the computer
                rather than be handled by this dialog box.

                Comment

                • JKing
                  Recognized Expert Top Contributor
                  • Jun 2007
                  • 1206

                  #9
                  Your string variable outputdir ends with a \, when you try to use it in the Path.Combine method it throws the illegal character error.

                  Comment

                  • Fuzz13
                    New Member
                    • Jun 2010
                    • 110

                    #10
                    If the outputdir ends with a \ wouldn't it always give me an illegal character error then? I can get the program to run if it is loading a file with only a single line of text.

                    Comment

                    • Fuzz13
                      New Member
                      • Jun 2010
                      • 110

                      #11
                      My code populates a corresponding text box with the directory stored as "outputdir" and it does not end with a "\" so I think the problem lies elsewhere.

                      Comment

                      • JKing
                        Recognized Expert Top Contributor
                        • Jun 2007
                        • 1206

                        #12
                        Originally posted by Fuzz13
                        My code populates a corresponding text box with the directory stored as "outputdir" and it does not end with a "\" so I think the problem lies elsewhere.
                        Do that with your other variables and you should be able to pin point the error.

                        Comment

                        • Fuzz13
                          New Member
                          • Jun 2010
                          • 110

                          #13
                          I am pretty sure I have found the line of code that is giving me the error.

                          Code:
                                          string fileName = lines[i] + ".txt";
                                                     
                                          string newFile = System.IO.Path.Combine(newPath, fileName);

                          The presence of "lines[i]" is the issue. If I instead use a string literal like this:

                          Code:
                                          string fileName = "something nice" + ".txt";
                                                     
                                          string newFile = System.IO.Path.Combine(newPath, fileName);
                          It will work just fine. The debugger says the error is in the second line of code where the two are combined but it's dependent on that "lines[i]" bit. It also crashes if I use "lines[0]" or any given value. That narrows it down but I don't know what to do about it. Any suggestions?

                          Comment

                          • JKing
                            Recognized Expert Top Contributor
                            • Jun 2007
                            • 1206

                            #14
                            Check the value of lines[i] and verify that there are no illegal characters in it.

                            Comment

                            • Fuzz13
                              New Member
                              • Jun 2010
                              • 110

                              #15
                              I have. There are none. The value of lines[i] appears as:

                              "This is text"
                              "This is more text"
                              "Again more text"

                              (the quotes are not part of the actual text)

                              Comment

                              Working...