作为作业的一部分 -
我似乎无法绕过3号。任何帮助或指示都非常感谢。
namespace unit9Assignment
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//add the extensions to the c box.
comboBox1.Items.Add(".txt");
comboBox1.Items.Add(".xyz");
comboBox1.Items.Add(".bat");
//make .txt the default selection
comboBox1.SelectedItem = ".txt";
tabControl1.SelectedIndexChanged += tabControl1_SelectedIndexChanged;
}
/******Tab Click Event********/
private void tabControl1_SelectedIndexChanged(Object sender, EventArgs e)
{
switch ((sender as TabControl).SelectedIndex)
{
case 0:
break;
case 1:
fileName(comboBox1.Text);
break;
case 2:
fileContent(Files.SelectedItem.ToString());
break;
}
}
/******Get Files Based on Selection*******/
public void fileName(string fileExt)
{
List<string> listOfFiles = new List<string>();
string[] fileExtArray = Directory.GetFiles(@"C:\Users\Public", "*" + fileExt);
foreach (string fileExtFile in fileExtArray)
{
listOfFiles.Add(fileExtFile);
}
Files.DataSource = listOfFiles;
}
/******Display 4 Lines @ 40 Characters Per Line*********/
public void fileContent(string fileName)
{
int numberOfLines = File.ReadLines(@fileName).Count(),
remainingLines = numberOfLines - 4;
//THIS PRINTS OUT 4 LINES @ 40 CHARACTERS PER LINE IF A FILE HAS LESS THAN 5 LINES
if (numberOfLines < 5)
{
foreach (string line in File.ReadLines(fileName))
{
richTextBox1.AppendText(line.Substring(0, 40) + Environment.NewLine);
Console.WriteLine(line.Substring(0, 40));
}
}
// NO CLUE WHAT TO DO
else
{
}
}
}
}
答案 0 :(得分:1)
这个怎么样:
public void fileContent(string fileName)
{
var lines = File.ReadLines(@fileName);
foreach (string line in lines.Take(4))
{
richTextBox1.AppendText(line.Substring(0, 40) + Environment.NewLine);
}
var remaining = lines.Count() - 4;
if (remaining > 0)
richTextBox1.AppendText(remaining + " more line(s) are not shown.");
}
Take()文档是here。
答案 1 :(得分:1)
给家庭作业的答案是不好的做法。相反,这里有一些指示可以帮助你解决问题:
//read a file
var lines = File.ReadLines("myfile");
//get the first 4 lines of your file
var first4 = lines.Take(4);
//get the first 40 characters of the first line of your file
var first40Chars = lines.FirstOrDefault().Take(40);
//get the remaining number of lines
var remainingCount = lines.Count() - 4;
拉出一个对话框来显示文件也很容易。 WinForms FileDialog可以帮助您。
答案 2 :(得分:1)
不是检查文件中的行数,为什么不继续开始打印,然后在4行后停止?像这样:
StreamReader fileIn = new StreamReader(fileName);
for(int i=0; i<4 && !fileIn.EndOfStream; ++i)
{
string line = fileIn.ReadLine();
if(line.Length > 40)
richTextBox1.AppendText(line.Substring(0,40) + Environment.NewLine);
else
richTextBox1.AppendText(line + Environment.NewLine);
}
int j;
for(j=0; !fileIn.EndOfStream; ++j)
fileIn.ReadLine();
if(j>0)
richTextBox1.AppendText(j.ToString() + " more lines are not shown.";
fileIn.Close();
...澄清一下,这将是你的整个fileContent方法。实际上,您不需要知道文件中的行数。当然,如果你的文件中的行数比int变量可以容纳的多,那么这个方法将不起作用,但我假设你没有使用这么长的文件。