2016-07-27 113 views
0

我有一個名爲one_two.config.txt的配置文件,其中包含要寫入的日誌文件的路徑。讀取配置文件並創建日誌文件

我想讀這一行('comdir = C:\ Users \ One \ Desktop'),然後在給定的目錄中創建一個新的日誌文件。 日誌文件都將有一些數據(時間/日期/ ID等)

這裏是我現在所擁有的:

    string VarSomeData = ""; // Contains Data that should be written in log.txt 

        for (Int32 i = 0; i < VarDataCount; i++) 
        {        

         csp2.DataPacket aPacket; 


         VarData = csp2.GetPacket(out aPacket, i, nComPort); 


         VarSomeData = String.Format("\"{0:ddMMyyyy}\",\"{0:HHmmss}\",\"{1}\",\"{2}\",\"{3}\" \r\n", aPacket.dtTimestamp, VarPersNr, aPacket.strBarData, VarId.TrimStart('0')); 


         string line = ""; 
         using (StreamReader sr = new StreamReader("one_two.config.txt")) 
         using (StreamWriter sw = new StreamWriter("log.txt")) 
         { 
          while ((line = sr.ReadLine()) != null) 
          { 
           if((line.StartsWith("comdir=")) 
           { 
           // This is wrong , how should i write it ? 
           sw.WriteLine(VarSomeData); 
           } 
          } 
         } 
        } 

現在在相同的目錄中創建日誌文件配置文件。

+1

是否要複製文件? –

+0

如果它爲你工作。比它好。而問題不是很清楚。請添加更多的細節讓我們瞭解。你究竟在尋找什麼。 –

+0

@AlekseyL。我想讀一個我已經寫過'comdir = C:\ Users \ One \ Desktop'的文件,閱讀這一行並在桌面上創建一個名爲'log.txt'的新文件。 –

回答

3

這應該讓你開始:

string line; 
using (StreamReader file = new StreamReader("one_two.config.txt")) 
using (StreamWriter newfile = new StreamWriter("log.txt")) 
{ 
    while ((line = file.ReadLine()) != null) 
    { 
     newfile.WriteLine(line); 
    } 
} 
0
//Input file path 
string inPath = "C:\\Users\\muthuraman\\Desktop\\one_two.config.txt"; 
//Output File path 
string outPath = "C:\\Users\\muthuraman\\Desktop\\log.txt"; 
// Below code reads all the lines in the text file and Store the text as array of strings 
string[] input=System.IO.File.ReadAllLines(inPath); 
//Below code write all the text in string array to the specified output file 
System.IO.File.WriteAllLines(outPath, input); 
+0

雖然此代碼片段可能會解決問題,但[包括解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要使用解釋性註釋來擠佔代碼,因爲這會降低代碼和解釋的可讀性! – FrankerZ

0

所以基本上,你有一個包含日誌文件中寫入的路徑中的配置文件;但是你沒有提到有關該日誌文件內容的任何信息。你只是想知道在哪裏創建它,對嗎?

喜歡的東西

string ConfigPath = "one_two.config.txt"; 
string LogPath = File.ReadAllLines(ConfigPath).Where(l => l.StartsWith("comdir=")).FirstOrDefault() 
if (!String.IsNullOrEmpty(LogPath)) { 
    using (TextWriter writer = File.CreateText(LogPath.SubString(7))) { 
    writer.WriteLine("Log file created."); 
    } 
} 

您還可以讀取配置線這種方式有一點點的代碼,但你會得到更好的性能

string LogPath = null; 
using (StreamReader file = new System.IO.StreamReader(ConfigPath)) { 
    while((line = file.ReadLine()) != null) { 
    if (line.StartsWith("comdir=")) 
     LogPath = line.Substring(7); 
    } 
} 

對於配置文件,您可能希望考慮使用您序列化爲XML文件的C#類,然後在啓動應用程序時反序列化。然後,只要有需要,您就可以在課程中獲得配置。

+0

你好。編輯過我的帖子,在那裏我展示了我現在擁有的東西。而日誌文件將包含數據,如(時間/日期/ ID等) –