Skip to content

Instantly share code, notes, and snippets.

@glebov21
Created June 16, 2022 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glebov21/70aba761beb7242cb1f29bfad9c9520a to your computer and use it in GitHub Desktop.
Save glebov21/70aba761beb7242cb1f29bfad9c9520a to your computer and use it in GitHub Desktop.
C# OpenFileDialog with multiselect OFN_ALLOWMULTISELECT lpstrFile
var ofn = new NativeMethods.OpenFileName();
ofn.lStructSize = Marshal.SizeOf(ofn);
if (Filter != null)
ofn.lpstrFilter = Filter.Replace('|', '\0') + "\0\0";
var maxFilePathLength = 250;
var maxFilesForMultiselect = 100;
ofn.nMaxFile = 1 * maxFilePathLength;
if (AllowMultiSelect)
{
ofn.Flags |= (
NativeMethods.OpenFileName.DialogFlags.OFN_ALLOWMULTISELECT |
NativeMethods.OpenFileName.DialogFlags.OFN_EXPLORER |
NativeMethods.OpenFileName.DialogFlags.OFN_PATHMUSTEXIST |
NativeMethods.OpenFileName.DialogFlags.OFN_FILEMUSTEXIST
);
ofn.nMaxFile = maxFilesForMultiselect * maxFilePathLength;
}
try
{
ofn.lpstrFileTitle = new string(new char[ofn.nMaxFile]);
ofn.nMaxFileTitle = ofn.nMaxFile;
ofn.lpstrFile = Marshal.AllocHGlobal(ofn.nMaxFile * Marshal.SystemDefaultCharSize);
// Initialize buffer with NULL bytes
for (int i = 0; i < ofn.nMaxFile * Marshal.SystemDefaultCharSize; i++)
Marshal.WriteByte(ofn.lpstrFile, i, 0);
ofn.lpstrInitialDir = InitialDirectory;
ofn.lpstrTitle = Text;
ofn.lpstrDefExt = "txt";
if (NativeMethods.GetOpenFileName(ofn))
{
DialogResult = DialogResult.OK;
List<string> selectedFilesList = new List<string>();
IntPtr filePointer = ofn.lpstrFile;
long pointer = (long)filePointer;
string file = Marshal.PtrToStringAuto(filePointer);
// Retrieve file names
while (file.Length > 0)
{
selectedFilesList.Add(file);
pointer += file.Length * Marshal.SystemDefaultCharSize + Marshal.SystemDefaultCharSize;
filePointer = (IntPtr)pointer;
file = Marshal.PtrToStringAuto(filePointer);
}
if (selectedFilesList.Count == 1)
{
FileName = selectedFilesList[0];
FileNamesMultiSelect = new string[] { FileName };
}
else
{
FileNamesMultiSelect = new string[selectedFilesList.Count - 1];
for (int i = 0; i < FileNamesMultiSelect.Length; i++)
{
FileNamesMultiSelect[i] = Path.Combine(selectedFilesList[0], selectedFilesList[i + 1]);
}
FileName = FileNamesMultiSelect[0];
}
}
}
finally
{
Marshal.FreeHGlobal(ofn.lpstrFile);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment