如何在C#代码中处理巨大的字符串数据. [英] How to Handle huge string Data in a C# code.

查看:86
本文介绍了如何在C#代码中处理巨大的字符串数据.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我遇到了这个问题.

我必须在文件中写入一个巨大的字符串.为此,我使用字符串生成器对象(使用stringbuilder.append方法)并为其分配巨大的字符串,然后使用流编写器将其写入文件中.

它可以正常工作,但是维护代码并不容易,并且代码看起来很脏.任何人都可以告诉我是否可以通过简单的方式完成此操作吗?
请让我知道是否需要其他输入?

片段

Hello All,

I have come across this problem.

I have to write a huge string into a file. For this I use the string builder object(using stringbuilder.append method) and assign the huge string to it and then, using stream writer, I write it onto the file.

It works fine but mainting the code is not easy and the code looks dirty. Can any one tell me if this can be done in a simple way?
Please let me know if you need any other inputs?

snippet

StringBuilder UptoMain = new StringBuilder();
StreamWriter file = new StreamWriter(@"c:\temp.txt", false);
UptoMain.AppendLine(@"Here there is lots and lots of text which makes 
the code look very ugly and and messy to hande");
file.WriteLine(UptoMain);

推荐答案

您也可以使用创建的文本文件作为输出作为输入.当然,这意味着您第一次输入的是文本文件,而不是硬编码的"字符串生成器.
You could start by using the text file you create as the output to be the input as well. Of course this would mean that for the first time, your input is the text file and not a "hard coded" string builder.


为什么需要对您的字符串进行硬连线程序?您无法从配置"文件中读取它们吗?
:)
Why do you need to hard-wire the strings in you program? Cannot you read them from a ''configuration'' file?
:)


我认为您根本不需要StringBuilder

以下代码:

I think you don''t need that StringBuilder at all!

The following code:

StringBuilder UptoMain = new StringBuilder();
StreamWriter file = new StreamWriter(@"c:\temp.txt", false);
UptoMain.AppendLine(@"Here there is lots and lots of text which makes the code look very ugly and and messy to hande");
file.WriteLine(UptoMain);



可以简化为:



can be reduced to:

StreamWriter file = new StreamWriter(@"c:\temp.txt", false);
string s = @"Here there is lots and lots of text which makes the code look very ugly and and messy to hande";
file.WriteLine(s);



但是,这不能解决长字符串的问题.如果您确实需要将字符串保留在代码中,您所能做的就是将字符串常量移动到其他位置.您可以这样写:



This does not sort your problem with the long string though... If you really need to keep the string in code, all you can do is to move the string constant somewhere else. You can write something like:

private const string MyString = @"Here there is lots and lots of text which makes the code look very ugly and and messy to hande";



...,然后在代码中使用MyString.这将使您的代码更具可读性,因为您可以将字符串常量声明移动到任意位置,甚至可以移动到单独的文件中.



...and then use MyString in the code later. This will make your code more readable, since you can move the string constant declaration anywhere you like, even to a separate file.


这篇关于如何在C#代码中处理巨大的字符串数据.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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