c # - Property.GetValue - Test for null pauser med indre undtagelse for null reference?

Indlæg af Hanne Mølgaard Plasc

Problem



Jeg skal scanne en masse Outlook '.msg' filer og bruger MsgReader biblioteket til at gøre det. (MsgReader Library Project on Github)
Jeg har skrevet følgende metode, der åbner beskeden, læser gennem hver af egenskaberne og uddrager nogen af ​​dem, der er markeret som 'streng', der skal tilføjes til en ordbog for at vende tilbage til den, der ringer op.
Her er koden: [4]


    public Dictionary<string, string> GetMsgFileDetails(string filepath)
    {
        Dictionary<string, string> filedetails = new Dictionary<string, string>();
        //try
        {
            string fullpath = Path.Combine(SelectedFolder, filepath);
            var msg = new Storage.Message(fullpath);
            foreach (var prop in msg.GetType().GetProperties())
            {
                string pname = prop.Name;

                if (prop.GetValue(msg) != null)
                {
                    object pvalue = prop.GetValue(msg);
                }
                // We only want the strings
                if (prop.GetValue(msg) != null && (prop.GetValue(msg) is string))
                {
                    filedetails.Add(prop.Name, prop.GetValue(msg).ToString());
                }

            }
            return filedetails;
        }
        //catch (Exception ex)
        //{
        //    MessageBox.Show(ex.Message, "Error trying to load file");
        //    return null;
        //}
    }

 (the try-catch block is commented out to allow easier debugging).


Det ser ud til at fungere fint, men det rammer en af ​​de værdier, der forårsager


   (prop.GetValue(msg) != null)


linje for at bryde med en System Reflection TargetInvocationException. Undtagelsesdetaljerne er som følger:





C:UsersBrettsource
eposFileMungerFileMungerViewModelsFolderContext.cs:line 208
at FileThing.ViewModels.FolderContext.GetProperties(String filepath, Boolean showwindow) in C:UsersBrettsource
eposFileMungerFileMungerViewModelsFolderContext.cs:line 159
at FileMunger.MainWindow.FileList\_Selected(Object sender, RoutedEventArgs e) in C:UsersBrettsource
eposFileMungerFileMungerMainWindow.xaml.cs:line 121
at system.Windows.Controls.SelectionChangedEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at System.Windows.Controls.ListBox.OnSelectionChanged(SelectionChangedEventArgs e)
at System.Windows.Controls.Primitives.Selector.InvokeSelectionChanged(List`1 unselectedInfos, List`1 selectedInfos)
at System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
at System.Windows.Controls.Primitives.Selector.SelectionChanger.SelectJustThisItem(ItemInfo info, Boolean assumeInItemsCollection)
at System.Windows.Controls.ListBox.MakeSingleSelection(ListBoxItem listItem)
at System.Windows.Controls.ListBox.NotifyListItemClicked(ListBoxItem item, MouseButton mouseButton)
at System.Windows.Controls.ListBoxItem.HandleMouseButtonDown(MouseButton mouseButton)
at System.Windows.Controls.ListBoxItem.OnMouseLeftButtonDown(MouseButtonEventArgs e)
at System.Windows.UIElement.OnMouseLeftButtonDownThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
at System.Windows.UIElement.OnMouseDownThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at FileMunger.App.Main()

Inner Exception 1:
 NullReferenceException: Object reference not set to an instance of an object.





Dette synes at skyldes værdien af ​​prop.GetValue evaluering til null, men det er det, jeg forsøger at teste på.
Jeg er klar over, at dette kan komme ind i dybden af ​​refleksion, hvor jeg ikke er ekspert, så hvis nogen har nogen ideer, hvordan man gør denne check, vil jeg virkelig sætte pris på det.
Skål.

Bedste reference


Jeg markerer dette som et svar, hvis nogen andre kommer over det samme problem. Der er faktisk en fejl i MsgReader biblioteket. Jeg har rejst spørgsmålet der, og der er et par løsninger, der har været meget venlige. Holdet skal også rette op på det, så det vil forhåbentlig kun være kortvarigt. Du kan se Github-tråden her [5]