.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

stringwriter and streamwriter..encoding?

Posted By:      Posted Date: April 10, 2011    Points: 0   Category :ADO.Net



when I do serialization my code looks like below. but problem is StringWriter makes it always UTF-16 and I need UTF-8. Simply I can replace it in string but I dont like to do this. I know that StreamWriter has encoding overload. on the other hand this code is used by multithreading and streamwriter isnt thread safe. what would be best option to encode my string. is xmltextWriter other option maybe? is there any small performance issue between all these 3?


thanks for your help


   Dim xmlSerializer As New XmlSerializer(GetType(itemTemplate))
    Dim stringWriter As New StringWriter
    xmlSerializer.Serialize(stringWriter, _object)
    Serialize = stringWriter.ToString()

"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

View Complete Post

More Related Resource Links

StreamReader.ReadLine(), StreamWriter.WriteLine() encoding issue


I have an ANSI text file which I read and change and write back the changes. The file originally is stored as follows:


Fine. Using StreamReader ctor without encoding parameter (which is not the same as Encoding.Default ) works fine (read+write) but the result is:

Line1<0D 0A>
Line2<0D 0A>
LineN<0D 0A>

So my question is how to force WriteLine() to write new line as 0A and not 0D 0A . Btw, when viewing a text file with 0A new lines using Notepad it is not displayed correctly. Notepad++ displays it correctly. The file does not have a BOM!

When using Encoding.UTF7 new lines are written as 0A but special characters like é is written as +AOk- which is not was I want.

The trick Write(0x0A) also not works because it will be written as characters '1' and '0' ("10" dec == 0A hex).

How to do it correctly? Many thanks!

Programming is a kind of art but not all programmers are a

Encoding en Decoding HTML



I stored in a database a ntext "<b>Hello</b>";

But when  I read it from the database I see <b>Hello</b> instead of Hello.

In the html source I see this: &lt;b&gt;Hello&lt;/b&gt;

Any Idea?


ASP.NET XML Writer Encoding Problem


Hi everybody,

I'm working on an ASP.NET application which writes xml sitemap to xml file. while I'm generating the loc element, I found that the writer converts the "&" in dynamic URLs to "&amp;" which I think it's not acceptable by Google. is there any way to get out of this?

Part of my code is as follow:

                writer.WriteString("/english/pages/pages.aspx?sid=" + drSections("SectionID").ToString + "&pageid=" + drPages("PageID").ToString + "")

and my output comes like :

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

Express Yourself: Encoding Videos Using Microsoft Expression Encoder 3 SDK


Video on the Web involves huge amounts of data. Learn the best way to manage and move that data with the help of Microsoft Expression Encoder 3.

Adam Miller

MSDN Magazine June 2010

The XML Files: Web Services Encoding and More


Aaron Skonnard covers the difference between document/literal and rpc/encoded Web Services and the history behind them.

Aaron Skonnard

MSDN Magazine May 2003

Encoding Problems in Razor



On my projects I am using SquisIt Framework and I have the following on page head:


      .Render("~/Styles/FlyOnDreams.FlyOnPages.Core.min.css")) %>

This is working. However when I use Razor view engine I am using the following:


How do I avoid chunked encoding either in HttpListener or in SimpleWorkerRequest?



I am writing a simple web server that uses HttpListner (http.sys) as a listener and an output conduit, and a SimpleWorkerRequest to process ASP.NET requests. All works well, but when an application my server hosts outputs chunked response, ASP.NET calls SimpleWorkerRequest's SendResponseFromMemory() method and passes in data that is chunked-encoded. When I write the output to HttpListener's output stream, it gets chunk-encoded again, breaking the whole thing. So I ended up writing chunked decoder in the middle, which makes it inefficient because the response gets massaged three times instead of one:

  1. Chunked-encoded by ASP.NET HttpResponse, then
  2. Decoded by my code in the SimpleWorkerRequest.SendResponseFromMemory(), and
  3. Gets chunked-encoded again by writing to HttpListner's output stream.

My question is how do I tell either SimpleWorkerRequest or HttpListener not to chunk-encode the response so the encoding can be done only once by either of those? (Preferably, it's SimpleWorkerRequest that needs an option to pass the response to the web server without changing it so that HttpListener would encode all responses, whether the come from ASP.NET or not, for example from CGI request processor).

Thank you,

encoding/decoding a string to/from bitmap


I have two methods:

Encode - takes a string, converts it to array of bytes, uses bytes to specify colors, creates a color and sets a pixel based on bytes

Decode - takes a pixel, retrieves color (R,G,B) bytes and converts them to characters, that produces a string which was previously encoded

I'm using two for loops (img height/width) to specify position and access pixels

The issue is that once display (Control Panel\Appearance and Personalization\Display) changes to anything other then "Smaller - 100%",
bytes have different values during decoding, thus different string is produced (corrupted).

If the setting is set to "Smaller - 100%" the results are normal.

What can I do to avoid that problem?

Thanks in advance

Info Path form when modified by using UTF-8 encoding having issues with existing 'iso-8859-1' char



I am modifying the infio path form 2007 from my state machine workflow to constantly update the status fields in the request form.

below is the method i created for the same..

private void updateInfoPathRequestForm(string xpathNode, string nodeValue)
            SPUserToken token = workflowProperties.Web.CurrentUser.UserToken;
            using (SPSite _site = new SPSite(workflowProperties.Site.ID, token))
                _site.AllowUnsafeUpdates = true;
                using (SPWeb _web = _site.OpenWeb(workflowProperties.Web.ID))
                    SPListItem item = _web.Lists[workflowProperties.List.ID].Items[workflowProperties.Item.UniqueId];

Encoding.ASCII.GetString(bytes) return string with not expected

Example   byte[] bytes = {  0x36,0x92,0x30,0x94}; string rs=  Encoding.ASCII.GetString(bytes) ; //result rs = ?60?   Is Wrong Result; Result Right is     '60". So this function should fix to properly decode two symbols ' and " Code ASCII ' is 0x92,Code ACII for " is  0x94

Storing and displaying user input (encoding query)

Hello,I've just been reading up a little on security regarding user input and how to handle html and scripts.My question is, what if I build my own CMS?Isn't it inevitable that I'll want to store html code, possibly scripts, and almost certainly apostrophes and special characters, and then display them again.What's the best way to do this, since I wont want to display the encoded html, but the html itself.Would it be to encode everything then when I want to actually display the html, decode it, but everywhere else, keep it encoded?I'm just trying to think of all the scenario's that I could come across when I accept user input where I don't know what they could be typing in.What if I WANT the user to be able to display html?Is it possible to decode only some tags but leave all other tags encoded? 

StreamWriter Error: Cannot close stream until all bytes are written.

 Hi, I have a testing platform that allows data to be posted to a real time collection system.  It uses the StreamWriter object to send both HTTP and XML formats, It works fine, but there is a new request to submit uploaded files.  This again works fine, unless the files are over 70k (we need to test upto 3MB).  If it is over 70k, the response is the content-length too big.   I have changed it so that the content-length is now set dynamically, dependant on the size of the file uploaded.  However, when the StreamWriter.Close() runs, the execption The request was aborted: The request was canceled. is generated, with the InnerException Cannot close stream until all bytes are written.From what I have found on the web, the solution is use StreamWriter.Flush(), but this code is already in place. Code is as follows:  With WebRequest .Method = "POST" .ContentType = "application/x-www-form-urlencoded" .PreAuthenticate = False .AuthenticationLevel = Security.AuthenticationLevel.None End With If FileSize &gt; 0 Then WebRequest.ContentLength = FileSize End If Try RequestStream = WebRequest.GetRequestStream() StreamWriter = New StreamWriter(RequestStream) StreamWriter.Write(strDataToPost)

UrlEncode does not appear to be encoding apostrophe's

All,I have spent quite a bit of time researching this here on Asp.Net's Forums, but also on the web in general, and I am still drawing a blank.The problem:  I am trying pass a values such as ... "Jacob's Carpentry" as a query string to another page.  However, the other pages keeps seeing "Jacob\\s Carpentry".What I have tried:  I have tried using both the Server.UrlEncode and HttpUtility.UrlEncode, and neither have worked.  I have also tried using them twice as was suggested in this article, but still with no luck.  Finally, I went so far as to try and encode the string, but then do a String.Replace on the " ' " apostrophe and substitute with a "%27".  This also did not work, as it appeared that the String.Replace wiped out the encoding.So I am stuck/lost.  It appears the standard PHP functions easily encode the apostrophe, but for some reason the .Net function isn't working.Here is the code I am using ..._postAReviewLinkButton.PostBackUrl = "~/ReviewskiPostReview.aspx?company=" + Server.UrlEncode(theCompany.CompanyName);As I understand it, when using the Request.QueryString method, it will automatically Decode the value as well, so when I read it, I am simply doing the following ...Company.GetByCompanyName(Request.QueryString["company"].ToString());I notice,

Content-Encoding Headers Being Removed?

Hello everyone. I've got a question.So I have an HttpModule that compresses the response with either gzip or deflate. Here's the code:     public class CompressionModule : IHttpModule    {        public void Dispose()        {        }        public void Init(HttpApplication context)        {            context.ReleaseRequestState += new EventHandler(context_ReleaseRequestState);            context.PreSendRequestHeaders += new EventHandler(context_PreSendRequestHeaders);        }        void context_ReleaseRequestState(object sender, EventArgs e)        {            // Get the application.            HttpApplication app = (HttpApplication)sender;            // The Accept-Encoding header from the client's browser.            string acceptE

Strings stripped of leading whitespace when using MTOM message encoding

Hello, I have a problem which I believe is actually caused by a bug in WCF 4 (.Net 4). I have a WCF service exposes two basicHttpBinding endpoints identical in everything but the message encoding used, one uses "text" and one "mtom" (i.e. the values for the messageEncoding attribute on the binding configuration). If I send a string with leading whitespaces to the "text endpoint" it is delivered to the service application code exactly as sent. If I send the string to the "mtom endpoint" it is stripped of the leading whitespaces before being handed over to the service application code. I have confirmed that the leading whitespaces are included in the message on the wire and using an IDispatchMessageInspector I have also confirmed that the whitespaces are still present after decoding the message (Message.ToString()). The whitespaces seem to disappear between this stage and when the message is deserialized. My current workaround is an IDispatchMessageInspector with the following AfterReceiveRequest method: public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { // Doing this roundtrip over MessageBuffer removes the problem // (i.e. leading whitespaces are not removed) request = request.CreateBufferedCopy(int.MaxValue).CreateMessage(); return null; } Am I missing something he

delete a csv file created via StreamWriter?

I don't know if this is the correct forum.. but, is there a way I can automatically delete the following .csv file that was created via streamwriter (after it is viewed by an individual)?CODE (I would like to automatically delete the_filename.csv)://///////////////////////////////////////////////////////////////////////////////////////////////            string filename = "~/downloadfiles/data_complex987654321_filename.csv";             StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath(filename));             StringBuilder sb = new StringBuilder();            string filename = "~/the_filename.csv";            StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath(filename));            StringBuilder sb = new StringBuilder();
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend