How to open a windows file open or save dialog without crashing Unity?

I want to open a file dialog on windows to open a file with. This is my current code:

var openFileDialog : System.Windows.Forms.OpenFileDialog = new System.Windows.Forms.OpenFileDialog();
openFileDialog.InitialDirectory = Application.dataPath;
openFileDialog.Filter = "text files (*.txt)|*.txt";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = false;

It actually works fine after building my project and kinda okay, when executing it the first time from within Unity, but with the following message in the log:

IsD3D9DeviceLost() || g_D3DInsideScene System.Windows.Forms.XplatUIWin32:Win32GetMessage(MSG&, IntPtr, Int32, Int32) System.Windows.Forms.XplatUIWin32:Win32GetMessage(MSG&, IntPtr, Int32, Int32) System.Windows.Forms.XplatUIWin32:GetMessage(MSG&, IntPtr, Int32, Int32, Boolean) System.Windows.Forms.XplatUIWin32:GetMessage(Object, MSG&, IntPtr, Int32, Int32) System.Windows.Forms.XplatUI:GetMessage(Object, MSG&, IntPtr, Int32, Int32) System.Windows.Forms.Application:RunLoop(Boolean, ApplicationContext) System.Windows.Forms.Form:ShowDialog(IWin32Window) System.Windows.Forms.CommonDialog:ShowDialog(IWin32Window) System.Windows.Forms.CommonDialog:ShowDialog()

The dialog shows up, I can choose my file and open it. If I now leave Unity and am moving a bit through my folder structure using the explorer, I usually get the standart win 7 message that Unity doesnt react anymore. If I dont do this, but open another dialog, I get tons of error messages and in the end the same windows message. The error messages I get then look like this (as popup windows):

Oops: Could not register the window class, win32 error 0

Sometimes the form shows up a second time and everything works as the first time, but then after the third time opening the dialog Unity crashes.

It would be great if anyone could tell me what I am doing wrong and maybe how to solve it :) Thanks.

Assuming you are using the script for the editor...

Take a look at the EditorUtility class' OpenFilePanel instead of using .NET functionality that might intervene with Unity's processes.

make sure to use mono's windows.forms.dll and not the .net one. it should works with both but test it. there is another way to use a C++ dll and call the open dialog and return the result in a dll function call.

The best thing to do is code a plugin that does this now that all versions of Unity support plugins. You can easily make this multi-platform for all computer OSes by using defines and setting the correct dll/bundle to load.

I’ve just made a plugin for OSX and it works great. Just make sure you build a universal bundle if you plan on making your game run on a 32bit machine.