private static StringBuilder Zapis = new StringBuilder(string.Empty); private static ManagementObjectSearcher GetMonitor = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DesktopMonitor"); foreach (ManagementObject queryObj in GetMonitor.Get()) { Zapis.AppendFormat("Разрешение экрана:" + string.Format(queryObj["ScreenWidth"] + "x" + queryObj["ScreenHeight"])); } 

After writing to the file, this line appears:

  • Screen resolution: x

      Разрешение экрана: 1920x1080 

An extra line is displayed 1st - Разрешение экрана: x How to remove this line? }

  • one
    Do you have 1 monitor in the properties of the system shown? PS: why do you need a format -function, if you do not use them for their intended purpose. Зы2: check the presence of the value before adding and filtering. if(queryObj["ScreenWidth"]) {zapis.append (...); } - teran
  • @teran, format used for the worst case) I tried the same thing without it :( But constantly getting the first line with an empty x - GooliveR
  • one
    so I asked if you had a second monitor in the device manager. The query returns 2 records to you, one is somehow mysterious, the second is sent to the current monitor. - teran
  • There are no 2 monitors in the device manager! Only one record: Универсальный монитор PnP ` - GooliveR
  • one
    The site is not accepted to enter the answer to the question, you have already put a daw - this is enough. - AK

2 answers 2

You have empty queryObj ["ScreenWidth"] and queryObj ["ScreenHeight"], write something like:

  foreach (ManagementObject queryObj in GetMonitor.Get()) { if(queryObj["ScreenWidth"] == null || queryObj["ScreenHeight"] == null) continue; Zapis.AppendFormat("Разрешение экрана:" + string.Format(queryObj["ScreenWidth"] + "x" + queryObj["ScreenHeight"])); // var str = $"Разрешение экрана: {queryObj["ScreenWidth"]} x {queryObj["ScreenHeight"]}"; // str.Dump(); } 
  • Thank you, this method helped solve this problem! - GooliveR
  • The answer, unfortunately, is from the area of ​​crutches, or the treatment of symptoms, and not sores. The correct solution would be to determine what object is returned with empty values, or how to select only the desired option. - teran

Put a stop point and go through the program. I think the ScreenWidth and ScreenHeight values ​​can be empty. Maybe there is some kind of virtual monitor.

And I would use this entry:

 Zapis.AppendFormat("Разрешение экрана: {0} х {1}", var1, var2); 
  • it is rather a monitor that was connected to the system sometime before. - teran