Author Topic: Method to check if File Name is Valid  (Read 19055 times)

0 Members and 1 Guest are viewing this topic.

Tharwat

  • Swamp Rat
  • Posts: 710
  • Hypersensitive
Method to check if File Name is Valid
« on: May 27, 2015, 08:22:19 AM »
Hello everyone .

Wow this is my first post in C# and hope to be a good user in this important and powerful programming language.  :-)

I have searched for a similar function as in AutoLISP ( getfiled ) to use in C# but did not find any , so I decided to write a similar program that mimic the same previous Autolisp function but to ask the user to enter a Valid File name was a challenge to me .

So I wrote the following Method to help me to check for a Valid File name as shown below .

Hope to have constructive comments that could improve my skills as well .

Thank you all.

Code - C#: [Select]
  1. private bool ValidFileName(string filename)
  2.         {
  3.             // Tharwat 27.05.2015 < My first Public Method in C# >    
  4.             // A method to check if the entered file name is valid to use.
  5.             // The method should return true / false as an output
  6.             bool valid = true;
  7.             List<string> Pattern = new List<string> { "^", "<", ">", ";", "|", "'", "/", ",", "\\", ":", "=", "?", "\"", "*" };
  8.             for (int i = 0; i < Pattern.Count; i++)
  9.             {
  10.                 if (filename.Contains(Pattern[i]))
  11.                 {
  12.                     valid = false;
  13.                     break;
  14.                 }
  15.             }
  16.             return valid;
  17.         }
  18.  

MexicanCustard

  • Swamp Rat
  • Posts: 705
Re: Method to check if File Name is Valid
« Reply #1 on: May 27, 2015, 08:54:20 AM »
Code - C#: [Select]
  1. private bool ValidFileName(string filename)
  2.         {
  3.             return System.IO.Path.GetInvalidFileNameChars(filename).Length == 0;
  4.         }
Revit 2019, AMEP 2019 64bit Win 10

Tharwat

  • Swamp Rat
  • Posts: 710
  • Hypersensitive
Re: Method to check if File Name is Valid
« Reply #2 on: May 27, 2015, 09:19:15 AM »
Thank you for the input .

But it seems that the Method GetInvalidFileNameChars holds an array of chars and it does not accept any argument as the error message indicated in the program .

MexicanCustard

  • Swamp Rat
  • Posts: 705
Re: Method to check if File Name is Valid
« Reply #3 on: May 27, 2015, 01:01:06 PM »
Thank you for the input .

But it seems that the Method GetInvalidFileNameChars holds an array of chars and it does not accept any argument as the error message indicated in the program .

Not sure what you mean when you say "holds an array of chars".  It returns an array of characters taken from within the string that are not accepted as file name characters.  Also, not sure what you're saying at "it does not accept any argument as the error message indicated in the program".  My method accepts the same parameters and returns the same type as the method you posted.  If you wanted the method to do something other than what you posted you should make that clear.
Revit 2019, AMEP 2019 64bit Win 10

Jeff_M

  • King Gator
  • Posts: 4096
  • C3D user & customizer
Re: Method to check if File Name is Valid
« Reply #4 on: May 27, 2015, 01:10:05 PM »
MC, Tharwat is saying that GetInvalidFileNameChars() does not accept any arguments, it merely returns an array of the invalid characters allowed.

Tharwat

  • Swamp Rat
  • Posts: 710
  • Hypersensitive
Re: Method to check if File Name is Valid
« Reply #5 on: May 27, 2015, 01:15:01 PM »
MC, Tharwat is saying that GetInvalidFileNameChars() does not accept any arguments, it merely returns an array of the invalid characters allowed.
Thank you Jeff for that nice explanation and that is exactly what I meant . :-)

To support what has been said before , here is the error message : No overload for method 'GetInvalidFileNameChars' takes 1 arguments .

 

Keith Brown

  • Swamp Rat
  • Posts: 601
Re: Method to check if File Name is Valid
« Reply #6 on: May 27, 2015, 03:06:15 PM »

Implimented as an extension of the string class.


Code - C#: [Select]
  1. namespace Brown.Extensions.StringExtensions
  2. {
  3.     using System.IO;
  4.  
  5.     /// <summary>
  6.     ///   Extensions to the default string class.
  7.     /// </summary>
  8.     public static class StringExtensions
  9.     {
  10.         /// <summary>
  11.         /// Validates the name and path of the file.
  12.         /// </summary>
  13.         /// <param name="fileName">Name of the file.</param>
  14.         /// <param name="filePath">Path of the file.</param>
  15.         /// <returns><c>true</c> if the file is valid, <c>false</c> otherwise.</returns>
  16.         private static bool IsValidFileNameWithPath(this string fileName, string filePath)
  17.         {
  18.             return (fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) &&
  19.                 (filePath.IndexOfAny(Path.GetInvalidPathChars()) >= 0) &&
  20.                 !File.Exists(Path.Combine(filePath, fileName));
  21.         }
  22.  
  23.         /// <summary>
  24.         /// Validates the name of the file.
  25.         /// </summary>
  26.         /// <param name="fileName">Name of the file.</param>
  27.         /// <returns><c>true</c> if the file name is valid, <c>false</c> otherwise.</returns>
  28.         private static bool IsValidFileName(this string fileName)
  29.         {
  30.             return (fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) &&
  31.                 !File.Exists(Path.Combine(fileName));
  32.         }
  33.  
  34.         /// <summary>
  35.         /// Validates the file path.
  36.         /// </summary>
  37.         /// <param name="filePath">The file path.</param>
  38.         /// <returns><c>true</c> if the path path is valid, <c>false</c> otherwise.</returns>
  39.         private static bool IsValidFilePath(this string filePath)
  40.         {
  41.             return (filePath.IndexOfAny(Path.GetInvalidPathChars()) >= 0) &&
  42.                 !File.Exists(Path.Combine(filePath));
  43.         }
  44.     }
  45. }
« Last Edit: May 27, 2015, 03:11:46 PM by Keith Brown »
Keith Brown | AutoCAD MEP Blog | RSS Feed
AutoCAD MEP 2014 / Revit MEP 2014 / EastCoast CAD/CAM addon / Visual Studio 2013

MexicanCustard

  • Swamp Rat
  • Posts: 705
Re: Method to check if File Name is Valid
« Reply #7 on: May 27, 2015, 03:09:12 PM »
MC, Tharwat is saying that GetInvalidFileNameChars() does not accept any arguments, it merely returns an array of the invalid characters allowed.

Ahhhh, I see now that I MSDN'ed the Method. My apologizes for mis-remembering how that method worked. Let's try again.
Code - C#: [Select]
  1. private bool ValidFileName(string filename)
  2.         {
  3.             var pattern = Path.GetInvalidFileNameChars();
  4.             return !filename.Any(pattern.Contains);
  5.         }


P.S. Keith posted while I was typing.  For the record Keith's way is the way I do it.
Revit 2019, AMEP 2019 64bit Win 10

BlackBox

  • King Gator
  • Posts: 3770
Re: Method to check if File Name is Valid
« Reply #8 on: May 27, 2015, 03:46:58 PM »
Wow this is my first post in C# and hope to be a good user in this important and powerful programming language.  :-)

Congrats, Tharwat!



"How we think determines what we do, and what we do determines what we get."

gile

  • Gator
  • Posts: 2507
  • Marseille, France
Re: Method to check if File Name is Valid
« Reply #9 on: May 27, 2015, 05:37:32 PM »
Using Regex

Code - C#: [Select]
  1. bool IsValidfileName(string fileName)
  2. {
  3.     return !Regex.IsMatch(
  4.         fileName,
  5.         string.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidFileNameChars()))));
  6.  }
Speaking English as a French Frog

Jeff H

  • Needs a day job
  • Posts: 6150
Re: Method to check if File Name is Valid
« Reply #10 on: May 27, 2015, 09:35:09 PM »
Playing around and no need for this unless maybe had to check millions of filenames daily,

A little something to find largest char's integer value from invalids chars, If gonna do this would probably use uint or whatever
a char is under the hood, but the max is 124.
Code - C#: [Select]
  1.         static int MaxInvaildChar()
  2.         {
  3.             int max = 0;
  4.             foreach (var invalidFileNameChar in System.IO.Path.GetInvalidFileNameChars())
  5.             {
  6.                 int cintv = Convert.ToInt32(invalidFileNameChar);
  7.                 if (cintv > max)
  8.                 {
  9.                     max = cintv;
  10.                 }
  11.             }
  12.             return max;
  13.         }
  14.  

And using a bool array
Code - C#: [Select]
  1.     class Program
  2.     {
  3.  
  4.         static bool[] invalids = new bool[125];
  5.  
  6.         static void Main(string[] args)
  7.         {
  8.  
  9.             foreach (var invalidFileNameChar in System.IO.Path.GetInvalidFileNameChars())
  10.             {
  11.                 invalids[Convert.ToInt32(invalidFileNameChar)] = true;
  12.             }
  13.  
  14.             string s1 = "hjghjhhjghjghjjg";
  15.             string s2 = "hjghjhhjghjg.mmmjk";
  16.             string s3 = "h^jghjhhjghjg.mmmjk";
  17.             string s4 = "hjghjhh<jghjg.mmmjk";
  18.             string s5 = "aaaaajghjhhjgh>jg.mmmjk";
  19.             string s6 = "ghjhhjgh|jg.mmmjk";
  20.             string s7 = "goooooodddddddjg.mmmjk";
  21.  
  22.             Console.WriteLine("{0} = {1}",s1, IsFileNameValid(s1));
  23.             Console.WriteLine("{0} = {1}", s2, IsFileNameValid(s2));
  24.             Console.WriteLine("{0} = {1}", s3, IsFileNameValid(s3));
  25.             Console.WriteLine("{0} = {1}", s4, IsFileNameValid(s4));
  26.             Console.WriteLine("{0} = {1}", s5, IsFileNameValid(s5));
  27.             Console.WriteLine("{0} = {1}", s6, IsFileNameValid(s6));
  28.             Console.WriteLine("{0} = {1}", s7, IsFileNameValid(s7));
  29.             Console.Read();
  30.  
  31.         }
  32.  
  33.         static bool IsFileNameValid(string fileName)
  34.         {
  35.             for (int i = 0; i < fileName.Length; i++)
  36.             {
  37.                 if (invalids[fileName[i]])
  38.                 {
  39.                     return false;
  40.                 }
  41.             }
  42.  
  43.             return true;
  44.         }
  45.  
  46.     }
  47.  

Tharwat

  • Swamp Rat
  • Posts: 710
  • Hypersensitive
Re: Method to check if File Name is Valid
« Reply #11 on: May 28, 2015, 04:45:31 AM »
A very nice work. :-)

Thank you all : Keith Brown , MexicanCustard , gile and Jeff H for writing these different approaches .

Just a question to Jeff H , would not be better to have a break function in the foreach loop inside the if function to end the loops if any invalid char found in the file name ?

Congrats, Tharwat!
Thank you Mat(e) for your greetings . :-)

I am regret about the time that I spent away from C# till now , although I have had lots of daily annoying messages and errors with VS.net till I got started understanding the mechanism between VS.net and AutoCAD .

Regards.

Jeff H

  • Needs a day job
  • Posts: 6150
Re: Method to check if File Name is Valid
« Reply #12 on: May 28, 2015, 09:26:17 AM »
You could replace your break with a return statement since it return the value and stop the loop.

Tharwat

  • Swamp Rat
  • Posts: 710
  • Hypersensitive
Re: Method to check if File Name is Valid
« Reply #13 on: May 28, 2015, 11:37:11 AM »
You could replace your break with a return statement since it return the value and stop the loop.

That's a very good idea to reduce the quantity of codes . :-) although my last reply was to ask you to include a break function into yours as mine if that considered right of course  .
Thank you.

Jeff H

  • Needs a day job
  • Posts: 6150
Re: Method to check if File Name is Valid
« Reply #14 on: May 28, 2015, 12:30:38 PM »
I just meant the return statement would break the loop and was using your example to help show how similar they are.