如何使用C#设置文件结尾? [英] How to set End Of File using C#?

查看:165
本文介绍了如何使用C#设置文件结尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用C#设置文件结尾?
我需要(快速)制作一个大文件,这是基于直接更改EOF的最快方法,而无需写入零字节.

How to set End Of File using C#?
I need to make (quickly) a large file, the fastest method based on changing EOF directly, without writing zero bytes.
HOW?

推荐答案

尽管它确实写了零,但在我的琐碎测试中却花了< 1秒写入10GB.因此,显然有一些优化正在完成.有一个Windows API,您可以p/调用,但由于它不会写入零,因此可以从以前未分配的磁盘空间中读取数据.由于存在安全隐患,因此需要提升的权限,而这可能并不是您真正想要的.这是我的操作方法:

使用(FileStream fileStream = File.Open(pathName,FileMode.OpenOrCreate,FileAccess.FileShare.
{
fileStream.SetLength(length);
fileStream.Close();
}

////注意,这也会缩小现有文件.
Although this does write zeros, in my trivial tests it took < 1 second to write 10GB. So there is clearly some optimization being done. There is a Windows API that you could p/Invoke but since it does not write zeroes, it is possible to read data from what was previously unallocated disk space. Since this is a security risk, it requires elevated permissions, which is probably not what you really want. Here is how I do it:

using (FileStream fileStream = File.Open(pathName, FileMode.OpenOrCreate, FileAccess.FileShare.
{
fileStream.SetLength(length);
fileStream.Close();
}

// Note this will also shrink an existing file.


尝试:
//Read from file
StreamReader sr = new(@"D:\myfile.txt");
//Single line from fileIO.txt 
String strLine;
//Continues to output one line at a time until end of file(EOF) is reached
while ((strLine = sr.ReadLine()) != null)
{
    Response.Write (strLine);
}
//Cleanup
sr.Close();



更新1:在这种情况下,您能否更新问题并详细说明您到底想做什么以及阻止您做什么?现在看来,您似乎需要如何在C#中获得EOF!

更新2:如果这是您的要求,为什么您需要EOF?使用类似这样的内容:



UPDATE 1: In that case, can you please update the question and elaborate on what exactly you are trying to do and whats stopping you? Right now, it just looks like you need how to get EOF in C#!

UPDATE 2: If thats your requirement, why do you need a EOF? Use something like this:

static void AppendToFile()
{
   StreamWriter sw;
   sw = File.AppendText(@"D:\myfile.txt");
   sw.WriteLine("This Line Is Appended");
   sw.Close();
   Console.WriteLine("Text Appended Successfully");
}


使用较大的文件而不关心内容,使用
Making a large file without caring about the content, can be achieved easily with FileStream.Seek[^]


The content will be zero or undefined, depending on the platform.

:)


这篇关于如何使用C#设置文件结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆