我刚接触 C# 才三天左右。我正在尝试打开一个关键字文件,然后让程序将关键字输入到程序的列表中。我不断收到一个看起来像这样的字符串。
"Discount Available\r\nDiscounts Available\r\n% OFF\r\n% off\r\nCoupon\r\ncoupon\r\nUse Coupon Code\r\nuse coupon code\r\ncoupon code\r\nCoupon Code\r\nOrders\r\norders\r\nOrder\r\norders\r\nreceived your order\r\nReceived Your Order\r\npayment received\r\nPayment Received\r\nLooking forward to your order's\r\nlooking forward to your order's\r\nLooking Forward To Your Order's\r\nReceived details\r\nreceived details\r\nReceived Details"
但我正在尝试让列表项输出到如下所示的列表中。
Discount Available
Discounts Available
% OFF
% off
Coupon
coupon
Use Coupon Code
use coupon code
coupon code
Coupon Code
Orders
orders
Order
orders
received your order
Received Your Order
payment received
Payment Received
Looking forward to your order's
looking forward to your order's
Looking Forward To Your Order's
Received details
received details
Received Details
这就是我目前所拥有的。任何帮助将非常感激。谢谢。
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
namespace Keywords
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OpenFileDialog ofd = new OpenFileDialog();
public void button1_Click(object sender, EventArgs e)
{
ofd.Filter = "TXT|*.txt";
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox2.Text = ofd.FileName;
string filePath = ofd.FileName;
string path = ofd.FileName;
string readText = File.ReadAllText(path);
List<string> fileItems = new List<string>();
fileItems.Add(readText);
foreach (string itemfile in fileItems)
{
}
fileItems = new List<string>();
}
}
}
}
感谢您所有的精彩回放,这就是我从每个人收到的答案中得到的新代码。我现在得到了想要的输出。这段代码是实现我想要实现的目标的最佳方法吗?谢谢你们!
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace Keywords
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OpenFileDialog ofd = new OpenFileDialog();
public void button1_Click(object sender, EventArgs e)
{
ofd.Filter = "TXT|*.txt";
if (ofd.ShowDialog() == DialogResult.OK)
{
string path = ofd.FileName;
List<string> fileItems = File.ReadAllLines(path).ToList();
}
}
}
}
我还有一个问题,有没有一种方法可以在不使用引号的情况下将项目添加到列表中?这是我得到的输出。
“有折扣”
“有折扣”
“% 离开” “% 离开” “优惠券”
“优惠券”
“使用优惠券代码”
“使用优惠券代码”
“优惠券代码”
“优惠券代码”
“命令”
“命令”
“命令” “命令”
“收到您的订单”
“收到您的订单”
“已收到付款”
“期待您的订单”
“期待您的订单”
“期待您的订单”
“收到的详细信息”
“收到详细信息”
“收到详细信息”
请您参考如下方法:
您可以使用 File.ReadLines() 在 IEnumerable<string> 中将每一行作为单独的字符串返回.如果你想让它成为 List ,就像现在一样,只需添加 .ToList() .
正如@mason 指出的那样,您需要添加 using System.Linq .
