All Things Techie With Huge, Unstructured, Intuitive Leaps

C# - Truncating FileName

Some people, especially lawyers and bankers who create documents, often have an essay for the filename.  Most systems are quite adept at handling very long filenames, but for practical reasons, I recently had to truncate a filename to 250 characters in a C# .Net program.

You simply cannot truncate with a substring, because you will lose the file extension.  Also, in the past, you could always bet that a file extension is always three characters preceded by a dot "," like .doc, or .jpg.  However now there is a good possiblity that you encounter a 5 character file extension including the dot.

So the algorithm is to get a string of the last 5 characters of the very long file name.  Then you get a substring of the first 245 characters.  The number in the substring is an index number that begins at zero, so it is 245 - 1 or 244.  Here is the code snippet:

if (filename.Length > 250)
   {
     
     String t1 = filename.Substring(0, 245);
     String t2 = filename.Substring(filname.Length - 6, 5);
     filename = t1 + t2;
   }

Hope this helps someone.

No comments:

Post a Comment