C # .NET-da matnli fayllar bilan ishlash
Xarajatlarni sizning uyingiz farovonligidan to'lash uchun sizga hamma narsani o'rgatamiz.
Ko'proq ma'lumotga ega bo'lish ...
Oldingi darsda, fayllar bilan ishlashga kirish, biz Windows operatsion tizimlarida yozish imtiyozlari bilan tanishdik. Ilova ma'lumotlarini qattiq diskda saqlashning eng oddiy usuli bu matnli fayllardan foydalanish. Sizlarning barchangiz .txt kengaytmasi bilan fayllarga duch kelganingizga aminman. Matn shunchaki bir nechta satrlarda saqlanadi. Chiziqlar, afsuski, OSga xos bo'lgan maxsus belgilar bilan ajratilgan. Yaxshiyamki, C # biz uchun bu muammoni hal qiladi.
Izoh: Internetdagi turli xil loyihalarda fayllarga yozish uchun turli xil sinflar va yondashuvlardan foydalangan holda duch kelishingiz mumkin. .NET doirasi vaqt o'tishi bilan ishlab chiqilgan va oldinga moslashuv maqsadida eski va yanada murakkab tuzilmalarni taqdim etadi. Men sizga eng oddiy va eng yangi yondashuvlarni ko'rsataman.
Writing text to a new file
First, let's create a new text file and write something into it. Create a new project (a console application) and name it TextFiles. The .NET framework provides the StreamWriter class for us which is used to write into text files.
Now, go ahead and add using System.IO into the source code. Next, we'll create a using block and create a new StreamWriter instance inside. As we already know from previous lessons, using will automatically close the file once the reading/writing is finished. We'll specify the path to our file in the constructor:
using (StreamWriter sw = new StreamWriter(@"file.txt"))
{
}
Our StreamWriter now points to the appropriate file. We write a new line in text files using the WriteLine() method. Once we're done writing, we'll have to call the Flush() method, which takes care of emptying the buffer. We won't have to deal with any of that, all we have to remember is that any written lines may remain in the buffer memory for a while, so we force to write them using the Flush() method.
At this point, the code looks something like this:
using (StreamWriter sw = new StreamWriter(@"file.txt"))
{
sw.WriteLine("The first line");
sw.WriteLine("This text is on the second line");
sw.WriteLine("And the third one.");
sw.Flush();
}
Once we run it, a file named file.txt will be created in our project folder, specifically, in the bin/debug folder. We have already gone over how to handle file path and writing privileges in C# .NET correctly, so we won't deal with any of that here so as to keep the code simple. As you can see, the file now exists and contains the text we designated:
Do'stlaringiz bilan baham: |