Encoding Method as variable

A

AhWau

I wrote a function to read content of web as below:

public static class Read
{
public static string WebContent(string PageLink, int EncodeType)
{
string Content = "";
int Counter = 0;

while (Content == "" && Counter <= 9999)
{
try
{
HttpWebRequest HWWebContent =
(HttpWebRequest)WebRequest.Create(PageLink);
HWWebContent.CachePolicy = new
System.Net.Cache.HttpRequestCachePolicy(System.Net.Cache.HttpRequestCacheLevel.NoCacheNoStore);
HWWebContent.Timeout = 3000;
HWWebContent.UserAgent = "Mozilla/4.0 (compatible;
MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)";
HttpWebResponse HWResponseWebContent =
(HttpWebResponse)HWWebContent.GetResponse();

StreamReader SRWebContent = new
StreamReader(HWResponseWebContent.GetResponseStream(), (EncodeType == 1) ?
Encoding.Default : Encoding.UTF8);
Content = SRWebContent.ReadToEnd();

SRWebContent.Close();
HWResponseWebContent.Close();
}
catch
{
Counter++;
Thread.Sleep(300);
}
}

return Content;
} // public static string WebContent(string PageLink)

}

now, i use this statement to selecting encoding method
(EncodeType == 1) ? Encoding.Default : Encoding.UTF8

but i want to select betwwen much more other encoding
and write a case or if statement at the begining of function like this

if(EncodeType ==1)
VAR = Encoding.Default;
else if(EncodeType ==2)
VAR = Encoding.UTF8;
else if(EncodeType ==3)
VAR = Encoding.ASCII;
else
..
..
..

is it possible?
Thank you so much
 
H

henk holterman

AhWau said:
I wrote a function to read content of web as below:

public static class Read
{
public static string WebContent(string PageLink, int EncodeType)



Ahwau,

like the other responses in this thread I don't get why you would want
to use an int to indicate a Encoding. Use the Encoding type itself or,
at least, use an enum.

But I would like to give a little advice on the rest of your code, it
looks like it could leak resources (Streams) and it could be simplified
a lot:

using (System.Net.WebClient wc = new System.Net.WebClient())
{
wc.Headers["UserAgent"] = "Mozilla ...";
wc.Encoding = Encoding.UTF8;
content = wc.DownloadString("http://...");
}



I left out the Counter/Retry logic but you can put that inside or
outside the using block. DownloadString manages its resources internally.


-hh-
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top