日期:2014-05-19  浏览次数:21132 次

请教如何在C#中删除一个文本文件最后一行
请教如何在C#中删除一个文本文件最后一行..呵呵

------解决方案--------------------
参考这个:
http://topic.csdn.net/t/20041207/10/3621707.html
------解决方案--------------------
参考 如下
byte[] buffer1,buffer2;
int iPosition=0;
FileStream fs = new FileStream(@ "C:\test.txt ",FileMode.Open, FileAccess.ReadWrite);
if (fs.Length> =1)
{
buffer1 = new byte[fs.Length];
fs.Seek(0, SeekOrigin.Begin);
fs.Read(buffer1, 0, buffer1.Length);
for (int i = buffer1.Length - 1; i > = 0; i--)
{
if (buffer1[i] == 10)//判断是否换行符
{
iPosition = i;
break;
}
}
buffer2 = new byte[iPosition];
for (int i = 0; i < buffer2.Length-1; i++)
{
buffer2[i] = buffer1[i];
}
fs.Close();
File.Delete(@ "C:\test.txt ");
fs = new FileStream(@ "C:\temp.txt ",FileMode.CreateNew);
fs.Seek(0, SeekOrigin.Begin);
fs.Write(buffer2, 0, buffer2.Length);
fs.Close();
File.Move(@ "C:\temp.txt ", @ "C:\test.txt ");

}
--------------------------------------------
太困了 写的不是很严谨 还有些情况没有写出判断
例如 最末尾是换行符的情况
------解决方案--------------------
其实还是要从第一行访问起,直到最后一行!
------解决方案--------------------
楼上兄弟给的很详细了
------解决方案--------------------
sealed class program{
static void Main(){
string fileName = @ "c:\test.txt ";
string[] allLines = System.IO.File.ReadAllLines(fileName);
System.Array.Resize(ref allLines, allLines.Length - 1);
System.IO.File.WriteAllLines(fileName, allLines);
}
}

// only for .net v2.0
------解决方案--------------------
在C/C++下好像有相应的函数,,
------解决方案--------------------
private void delete()
{
private ArrayList _arrBarcode = new ArrayList();

if (System.IO.File.Exists( "文件 "))
{
System.IO.StreamReader objectReader = new System.IO.StreamReader( "文件 ", System.Text.Encoding.UTF8);
while (sLine != null)
{
sLine = objectReader.ReadLine();
if (sLine != null)
_arrBarcode.Add(sLine);
}

objectReader.Close();
}
}
------解决方案--------------------
private void delete()
{
private ArrayList _arrBarcode = new ArrayList();
private string sLine = " ";
if (System.IO.File.Exists( "文件 "))
{
System.IO.StreamReader objectReader = new System.IO.StreamReader( "文件 ", System.Text.Encoding.UTF8);
while (sLine != null)
{
sLine = objectReader.ReadLine();
if (sLine != null)
_arrBarcode.Add(sLine);
}
objectReader.Close();
}
_arrBarcode.RemoveAt(_arrBarcode.Count - 1);
if (_arrBarcode.Count > 0)
{
System.IO.StreamWriter objectWriter = new System.IO.StreamWriter( "文件, false, System.Text.Encoding.UTF8);
for (int i = 0; i < _arrBarcode.Count; i++)