Ok how can i prevent code duplication in this particular case
The duplication happens due to streamreader character encoding.
In some cases i want to use default and in some cases i want to define myself.
irCustomEncoding
is an integer
When i do not provide encoding what does application do as default ?
using (Stream strumien = response.GetResponseStream())
{
if (irCustomEncoding == 0)
{
using (StreamReader sr = new StreamReader(strumien))
{
srBody = sr.ReadToEnd();
}
}
else
{
using (StreamReader sr = new StreamReader(
strumien, System.Text.Encoding.GetEncoding(irCustomEncoding)))
{
srBody = sr.ReadToEnd();
}
}
}
So what i am asking is how can i write single using (StreamReader...
instead of duplicating code
ty very much
c# wpf .net 4.5
Just use Encoding.UTF8
if you don't have a different one:
var encoding = irCustomEncoding == 0 ? Encoding.UTF8
: Encoding.GetEncoding(irCustomEncoding);
using (TextReader reader = new StreamReader(strumien, encoding))
{
srBody = reader.ReadToEnd();
}
(Encoding.UTF8
is the default if you don't specify an encoding for StreamReader
.)
Alternatively, you could get UTF8 by its codepage number:
var codePage = irCustomEncoding == 0 ? Encoding.UTF8.CodePage : irCustomEncoding;
var encoding = Encoding.GetEncoding(codePage);
// Rest of the code as before
using (...)
{
...
}
See more on this question at Stackoverflow