В рамках .net с помощью приложения Windows Forms я могу очистить файл, а затем записать данные, которые я хочу вернуть в этот файл.Как удалить все строки в файле, а затем переписать файл в Compact Framework 3.5 C#
Вот код, который я использую в Windows Forms:
var openFile = File.OpenText(fullFileName);
var fileEmpty = openFile.ReadLine();
if (fileEmpty != null)
{
var lines = File.ReadAllLines(fullFileName).Skip(4); //Will skip the first 4 then rewrite the file
openFile.Close();//Close the reading of the file
File.WriteAllLines(fullFileName, lines); //Reopen the file to write the lines
openFile.Close();//Close the rewriting of the file
}
openFile.Close();
openFile.Dispose();
Я пытаюсь сделать то же самое компактную рамку. Я могу сохранить строки, которые я хочу, а затем удалить все строки в файле. Однако я не могу переписать файл.
Вот моя компактная структура кода:
var sb = new StringBuilder();
using (var sr = new StreamReader(fullFileName))
{
// read the first 4 lines but do nothing with them; basically, skip them
for (int i = 0; i < 4; i++)
sr.ReadLine();
string line1;
while ((line1 = sr.ReadLine()) != null)
{
sb.AppendLine(line1);
}
}
string allines = sb.ToString();
openFile.Close();//Close the reading of the file
openFile.Dispose();
//Reopen the file to write the lines
var writer = new StreamWriter(fullFileName, false); //Don't append!
foreach (char line2 in allines)
{
writer.WriteLine(line2);
}
openFile.Close();//Close the rewriting of the file
}
openFile.Close();
openFile.Dispose();
Что вы подразумеваете под «Я не могу»? Что происходит? (Вы также должны использовать инструкции 'using' для вашего автора ... и неясно, почему вы закрываете его три раза. Это не помогает вам не форматировать ваш код и не показывать, где' openFile' сначала открылся ...) –