从流中获取字符串 [英] Get string from a stream

查看:116
本文介绍了从流中获取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我在将流转换为字符串时遇到问题.下面给出的是我使用过的代码...

hello,

I have a problem with converting a stream to string. The below given is the code I have used...

public String GetStringfromStream(Stream strLogContent)
        {
            StreamReader sr = new StreamReader(strLogContent);
            String strQuery = sr.ReadToEnd();
            sr.Dispose();
            return strQuery;
        }


但这会引发错误消息 流不可读 .
从第二行引发异常..(" String strQuery = sr.ReadToEnd(); ")
有人可以帮我吗?

问候
Sebastian


But it throws an error message Stream was not readable.
The exception is thrown from second line..("String strQuery = sr.ReadToEnd();")
Can anyone help me on this?

Regards
Sebastian

推荐答案

public String GetStringfromFile(string filePath)
{
    using(StreamReader sr = new StreamReader(filePath))
    {           
       return sr.ReadToEnd();
    } 
}


公共字符串GetStringfromStream(Stream strLogContent)
{
使用(StreamReader sr = new StreamReader(strLogContent))
{
返回sr.ReadToEnd();
}
}
public String GetStringfromStream(Stream strLogContent)
{
using (StreamReader sr = new StreamReader(strLogContent))
{
return sr.ReadToEnd();
}
}


首先,这是否与日志记录有关?如果是这样,请不要执行这些流.使用类System.Diagnostics.EventLog;请参阅:
http://msdn.microsoft.com/en-us/library/system.diagnostics. eventlog.aspx [ ^ ].

对于高级用途(包括文件用途),请参阅我过去的回答:
将MsBuild OutPut即时发送到TextBox Windows应用程序中 [ ^ ],
如何在文件夹下创建事件日志 [ ^ ].

现在,关于您的流的问题.您的代码不太正确(如Dean演示的那样,您没有使用可以通过using语句完成的异常处理),但是问题不在您显示的代码中.问题是在调用方法之前必须创建的流的实际运行时类型和模式.要查看该问题,我需要查看如何构造该对象.如果可以与文件一起使用,Dean的答案将提供一个完美的代码示例.

—SA
First of all, is it all about logging? If so, don''t do those streams. Use the class System.Diagnostics.EventLog; please see:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx[^].

For advanced uses (including uses of a file), please see my past answers:
MsBuild OutPut to the TextBox on the fly in Windows Application[^],
How to create event log under a folder[^].

Now, about the problem with the stream you have. Your code is not quite correct (you are not using exception handling which could be done via the using statement, as Dean have demonstrated), but the problem is not in the code you have shown. The problem is the actual run-time type and mode of the stream you had to create before calling your method. To see the problem, I would need to see how you construct this object. If you can use with file, the answer by Dean provides a perfect code sample.

—SA


这篇关于从流中获取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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