2016-08-10 72 views
0

這個應用程序向一個返回數據的API發送一個請求。我想將這些數據保存到xml文件中。 問題是,我每次運行應用程序時,都想創建一個新的xml文件,而不是替換當前的「c:\ temp \ xml.xml」。最好我希望他們被當前日期命名,所以而不是1 xml.xml我想要20160810.xml,第二天當我運行應用程序時,我想要另一個名爲20160811.xml的xml文件。我怎麼做?如何創建幾個XML文件並對它們進行日期標記?

static void Main(string[] args) 
    { 
     RunAsync().Wait(); 
    } 

    static async Task RunAsync() 
    { 
     using (var client = new HttpClient()) 
     { 
      //Send HTTPrequest 
      client.BaseAddress = new Uri("http://xxxxx"); 
      client.DefaultRequestHeaders.Accept.Clear(); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

      HttpResponseMessage response = await client.GetAsync("api/people/peoples?Firstname=Adam"); 

      if (response.IsSuccessStatusCode) 
      { 
       var person = response.Content.ReadAsAsync<IEnumerable<Persons>>().Result; 

       XmlDocument xmldoc = new XmlDocument(); 
       foreach (var i in person) 
       { 
        XmlElement el = (XmlElement)xmldoc.AppendChild(xmldoc.CreateElement("Employee")); 
        el.SetAttribute("EmployeeID", i.Peopleid); 
        el.AppendChild(xmldoc.CreateElement("Firstname")).InnerText = i.FirstName; 
        el.AppendChild(xmldoc.CreateElement("Lastname")).InnerText = i.LastName; 
        el.AppendChild(xmldoc.CreateElement("Address")).InnerText = i.LocationName; 

        Console.WriteLine("{0}\t{1}:\t{2}\t-{3}", i.FirstName, i.LastName, i.Peopleid, i.LocationName); 
        xmldoc.Save("c:\\temp\\xml.xml"); 
       } 

      } 
     } 


    } 

class Persons 
{ 
    public string Peopleid { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string LocationName { get; set; } 


} 
+0

所以你的問題是「如何將當前日期轉換爲字符串在C#」? – Tomalak

回答

0

DateTime.Now給出當前日期和時間,所以修改保存到

xmldoc.Save("c:\\temp\\"+DateTime.Now.ToString("yyyyMMdd") + ".xml"); 
相關問題