2014-03-12 50 views
0

在我的應用程序中,我確定網絡更改發生時。我有,我用一些示例代碼,但我想結果字符串以一定的方式格式化如何格式化字符串

string change = string.Empty; 
     switch (e.NotificationType) 
     { 
      case NetworkNotificationType.InterfaceConnected: 
       change = "Connected to "; 
       break; 
      case NetworkNotificationType.InterfaceDisconnected: 
       change = "Disconnected from "; 
       break; 
      case NetworkNotificationType.CharacteristicUpdate: 
       change = "Characteristics changed for "; 
       break; 
      default: 
       change = "Unknown change with "; 
       break; 
     } 

     string changeInformation = String.Format(" {0} {1} {2} ({3})", 
        DateTime.Now.ToString(), change, e.NetworkInterface.InterfaceName, 
        e.NetworkInterface.InterfaceType.ToString()); 

     // We are making UI updates, so make sure these happen on the UI thread. 
     Dispatcher.BeginInvoke(() => 
     { 
      Changes.Add(changeInformation); //Changes contains the changeInformation 
     }); 

目前的結果看起來像

enter image description here

但這不是在格式化好所有,而且往往會有時混亂。我希望能夠對其進行格式化,以使DateTime.Now.ToString()位於最上面,然後是change位於下一行,然後是e.NetworkInterface.InterfaceNamee.NetworkInterface.InterfaceType.ToString()。我怎麼能這樣做?

+1

使用換行符...( \ n幫助) – Vogel612

+1

'String.Format(「{0} \ n {1} \ n {2}({3})」,...' –

回答

1

使用明確\r\n或更好,Environment.NewLine,例如,

String.Format(" {0}{1}{2}{3}{4}({5})", 
       DateTime.Now, Environment.NewLine, 
       change, Environment.NewLine, 
       e.NetworkInterface.InterfaceName, 
       e.NetworkInterface.InterfaceType); 

還要注意的是,你不需要在參數赤裸裸.ToString() - 這是在String.Format()

0

暗示我認爲你必須添加新行

string changeInformation = String.Format(" {0} {1} {2} {3} ({4})", 
        DateTime.Now.ToString(), Environment.NewLine, change, e.NetworkInterface.InterfaceName, 
        e.NetworkInterface.InterfaceType.ToString());