如何替换文本文件内容 [英] How to replace a textfile content
问题描述
如何用字符串替换文本文件的数字?
输入文件:
索引1-25(1-25是页码范围)
类别26-50
页码应根据以下条件替换:
if(pageno> 1和pageno&=; 25)
字符串rep =" ";
s.replace(s,pageno,rep);
否则if(pageno> 25和pageno&=; 50)
字符串rep =" ";
s.replace(s,pageno,rep);
如果
结束
输出文件:
索引 index.html
类别 categories.html
但是我们如何读取/识别页码并将其获取到 pageno 这样的变量中?
Hi,
How can we replace numbers of a text file with strings?
Input file :
index 1-25 (the 1-25 is the page number range)
categories 26-50
The page numbers should replace based on conditions like:
if(pageno > 1 and pageno <= 25)
string rep="";
s.replace(s,pageno,rep);
else if(pageno > 25 and pageno <= 50)
string rep="";
s.replace(s,pageno,rep);
end if
Out file :
index index.html
categories categories.html
but how can we read/identify the page numbers and to get them to a variable like pageno ?
推荐答案
如果文件不是太大,则可以使用类System.IO.StreamReader
打开它,并使用System.IO.StreamReader.ReadToEnd
读取全部内容,替换您需要的任何内容,然后使用类System.IO.StreamWriter
将内容写回.请参阅:
http://msdn.microsoft.com/en-us/library/system.io. streamreader.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/system.io. streamwriter.aspx [^ ].
如果文件很大,则可以使用类System.IO.FileStream
在读写模式下使用流.您将需要在文件模式System.IO.FileMode.Open
和文件访问权限System.IO.FileAccess.ReadWrite
中使用构造函数System.IO.FileStream.FileStream(string path, System.IO.FileMode mode, System.IO.FileAcces access)
.请参阅:
http://msdn.microsoft.com/en-us/library/system.io. filestream.aspx [^ ],
http://msdn.microsoft.com/en-us/library/tyhc0kft.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/system.io. filemode.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/4z36sx0f.aspx [ ^ ].
您可以使用属性
If the file is not too big, you can open it with the classSystem.IO.StreamReader
read the whole content usingSystem.IO.StreamReader.ReadToEnd
, replace whatever you need and write the content back using the classSystem.IO.StreamWriter
. Please see:
http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx[^],
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx[^].
If the file is big, you can use a stream in read-write mode using the classSystem.IO.FileStream
. You will need to use the constructorSystem.IO.FileStream.FileStream(string path, System.IO.FileMode mode, System.IO.FileAcces access)
with the file modeSystem.IO.FileMode.Open
and file accessSystem.IO.FileAccess.ReadWrite
. Please see:
http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx[^],
http://msdn.microsoft.com/en-us/library/tyhc0kft.aspx[^],
http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx[^],
http://msdn.microsoft.com/en-us/library/4z36sx0f.aspx[^].
You can read and write from any position using the property
System.IO.FileStream.Position<code>.<br />
<br />
<dd>—SA</dd>
这篇关于如何替换文本文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!