PDA

View Full Version : سوال: سوال درمورد نحوه خواندن خط به خط فایل متنی



samma20
سه شنبه 19 آبان 1394, 09:29 صبح
سلام.
من یه برنامه نوشتم که در آن میخوام یک فایل متنی را بگیرد و هر بار یک خط آن را خوانده و کاری روی آن خط انجام دهد و سپس به خط بعدی برود. طبق کدهایی که در اینترنت پیدا کردم -که sr.readline! یه همچین کدی بود - باز هم وقتی تست کردم دیدم که فقط خط اول رو میخونه. در ضمن طول هر یک از خطوط در فایل متنی بنده مشخص نیست.
کد منبه صورت زیر است:


public int NumberOfItems(string s)
{


//string line;//current line
string item = "";//temporary string for read total characters of item
int readerString = 0;//read char to char of string
int readerArray = 0;//check Items array for duoplicated items
int index = 0;//index for save item into the array
Boolean flagIsDuplicated = false;
items = new string[10000];






//read line to line of selected data set
//while ((line = file.ReadLine()) != null)
//{
//read selected line
while (readerString < s.Length)
{
//read item
if (s.ElementAt(readerString).Equals(' '))
{
//check duplicated items
for (readerArray = 0; readerArray <= index; readerArray++)
{
if (item.Equals(items[readerArray]))
{
item = "";
flagIsDuplicated = true;
break;
}
}
if (flagIsDuplicated == false)
{
numberOfItems++;
index++;
item = "";
}
}
else
{
item += s.ElementAt(readerString);
}
readerString++;
if (readerString == s.Length)
{
flagIsDuplicated = false;
//check duplicated items
for (readerArray = 0; readerArray <= readerString; readerArray++)
{
if (item.Equals(items[readerArray]))
{
item = "";
flagIsDuplicated = true;
break;
}
}
if (flagIsDuplicated == false)
{
items[index] = item;
numberOfItems++;
item = "";
}
}


}//end of while
//}//ond of while
return numberOfItems;
}//end of NumberOfItems

محمد رضا فاتحی
سه شنبه 19 آبان 1394, 09:53 صبح
سلام راحت ترین راه
string[] line = File.ReadAllLines(path);

یه آرایه بهت بر می گردونه

Mahmoud.Afrad
سه شنبه 19 آبان 1394, 15:04 عصر
using (StreamReader sr = new StreamReader(File.OpenRead(@"FilePath")))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
// ...
}
}

samma20
پنج شنبه 21 آبان 1394, 17:35 عصر
سلام راحت ترین راه
string[] line = File.ReadAllLines(path);

یه آرایه بهت بر می گردونه
از اینکه جوابمو دادین ممنونم ولی راستش این کد را هم امتحان کردم. درواقع با این روش کل فایل متنی در یک ارایه می اید!!!!:گریه:

samma20
پنج شنبه 21 آبان 1394, 17:37 عصر
این روش را هم امتحان کردم ولی بازم درست نمیشه!!!
خواهش میکنم کمکم کنید.:گریه::گریه::گریه:

mr_ayma
پنج شنبه 21 آبان 1394, 22:17 عصر
تو هر دو کدی که دوستان نوشتند راحت میشه از طریق عناصر آرایه به خط ها دسترسی داشت مثل این




string[] line = File.ReadAllLines("test.txt");
for (int i = 0; i < line.Length; i++)
{
MessageBox.Show(line[i].ToString());
}