![](/img/trans.png)
[英]How to add more than one element to my list/array in C# while reading a file, so I can print all on one line per line of the text?
[英]How can i check if a text file contain more then one line of text inside?
我有這個代碼:
BeginInvoke(new Action(() => tempNamesAndTexts.ForEach(Item => textBox1.AppendText(DateTime.Now + "===> " + Item + Environment.NewLine))));
foreach (string items in tempNamesAndTexts)
{
Logger.Write(items);
}
一旦我運行該程序,它將執行:Logger.Write(items); 然后文本文件將如下所示:
Danie hello Ron hi Yael再見Josh大家好
下次運行程序時,它會向文本文件寫入相同的字符串。 我想檢查文本文件中是否已存在此字符串不要再寫入,否則寫入,這樣結果將是每次運行程序時它將寫入記錄器(文本文件),如果有的話只有新字符串。
這是記錄器文本文件的字符串變量:
full_path_log_file_name
這個變量里面有:
C:\\Users\\Chocolade\\AppData\\Local\\ChatrollLogger\\ChatrollLogger\\log\\logger.txt
這是完整的代碼,直到這部分是DoWork在運行程序時總是做一次的部分:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using DannyGeneral;
namespace ChatrollLogger
{
public partial class Form1 : Form
{
string log_file_name = @"\logger.txt";
string full_path_log_file_name;
string path_log;
bool result;
List<string> namesAndTexts;
WebResponse response;
StreamReader reader;
string profileName;
string profileNameText;
string url;
string testingUrl;
int index;
List<string> names;
List<string> texts;
WebClient wc;
public Form1()
{
InitializeComponent();
Logger.exist();
wc = new WebClient();
result = true;
url = "http://chatroll.com/rotternet";
testingUrl = "http://chatroll.com/testings";
backgroundWorker1.RunWorkerAsync();
path_log = Path.GetDirectoryName(Application.LocalUserAppDataPath) + @"\log";
full_path_log_file_name = path_log + log_file_name;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
List<string> tempNamesAndTexts = new List<string>();
string tempDownload = downloadContent();
GetProfileNames(tempDownload);
GetTextFromProfile(tempDownload);
for (int i = 0; i < names.Count; i++)
{
tempNamesAndTexts.Add(names[i] + " " + texts[i]);
}
if (InvokeRequired)
{
BeginInvoke(new Action(() => tempNamesAndTexts.ForEach(Item => textBox1.AppendText(DateTime.Now + "===> " + Item + Environment.NewLine))));
foreach (string items in tempNamesAndTexts)
{
Logger.Write(items);
string t = full_path_log_file_name;
}
}
string[] array = File.ReadAllLines("test.txt");
if(array.Length > 0)
{
// lines exist
}
像這樣的東西?
string path = "test.txt";
string valueToWrite = "....";
//only write to the file, if the specified string is not already there
if(!File.ReadLines(path).Any(l => string.Equals(l, valueToWrite)))
{
File.AppendAllText(path, valueToWrite);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.