[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Convert between long and short file names in C#

[Convert between long and short file names in C#]

You can use the GetShortPathName API function to convert from long to short file names. The following code declares the API function.

// Define GetShortPathName API function. [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern uint GetShortPathName(string lpszLongPath, char[] lpszShortPath, int cchBuffer);

The following ShortFileName method uses the API function to convert a long file name into a short one.

// Return the short file name for a long file name. private string ShortFileName(string long_name) { char[] name_chars = new char[1024]; long length = GetShortPathName( long_name, name_chars, name_chars.Length); string short_name = new string(name_chars); return short_name.Substring(0, (int)length); }

This code creates a character buffer to hold the short file name. It calls the API function, converts the buffer into a string, and then truncates it to its proper length.

In addition to GetShortPathName, there's a GetLongPathName API function that converts from a short file name to a long one, but there's an even easier way to do this. Simply create a FileInfo object for the file name and then use its FullName property. The LongFileName method shown in the following code uses this approach.

// Return the long file name for a short file name. private string LongFileName(string short_name) { return new FileInfo(short_name).FullName; }

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.