Cannot assign to XXX because it is a using variable

I get that error when compiling my app.  I'm trying to use a Using statement with a Stream object so that I can make sure it gets completely killed and disposed as soon as I'm done with it.

I've attached the source code below.  Can someone show me what i'm doing wrong and correct it.
string proxyUrl = HttpContext.Current.Server.UrlDecode(url);
        HttpWebRequest webReq;
        HttpWebResponse webResp;
        bool success = false;
        using(Stream streamHttp = null){
        //try
        //{

        webReq = (HttpWebRequest)WebRequest.Create(proxyUrl);
        webReq.Timeout = Convert.ToInt32(WebConfigurationManager.AppSettings["TimeOut"]);
        webResp = (HttpWebResponse)webReq.GetResponse();
        if (webResp.StatusCode == HttpStatusCode.OK)
        {
            streamHttp = webResp.GetResponseStream();
            //HttpContext.Current.Response.Write("OK");
            //HttpContext.Current.Response.End();
            success = true;
        }
      
        // Do not write anything if we failed the request. We may want to use old data
        // Watch for io errors. The file may be locked
        if (success)
        {
              
            HttpContext.Current.Application["OfflineCount"] = 0;    // Clear any flags when we were off line 
            String filePath = "";

            /* Begin XML validation */
            // Copy streamHttp to a memory stream to allow seeking when using in XMLTextReader
            streamHttp = copyToMemoryStream(streamHttp);
            if (!xmlIsValid(url, streamHttp, durationSeconds))
            {
                schemReader.Close();
                // Write to log when data is invalid
                cimLog.WriteLog("\tFeed provider for feed: " + url + " returned invalid data.");
                // Break out of function to ensure proxy does not cacher bad data
                return;
            }
            schemReader.Close();
            // Reset position of streamHttp;
            streamHttp.Position = 0;
            //try
            //{
            filePath = WebConfigurationManager.AppSettings["CachePath"].ToString() + cimHTTP.ConvertUrlToFileName(url);
                FileStream streamCache = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                BinaryWriter binCache = new BinaryWriter(streamCache);
                int b;
                while ((b = streamHttp.ReadByte()) != -1)
                {
                    binCache.Write(Convert.ToByte(b));
                }
                binCache.Close();
                streamHttp.Close();
            //}
            //catch (IOException ioError)
            //{
                //cimLog.WriteLog("Could not write to " + filePath + ". " + ioError.Message, cimLog.LogType.Warning);
            //}
            //catch (Exception exError)
            //{
            //    cimLog.WriteLog(exError.Message);
            //}
            }
        }

Open in new window

davidcahanAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

käµfm³d 👽Commented:
A "using" statement should look like:
using(Stream streamHttp = new FileStream("C:\my\path\to_file.txt", FileMode.Read))
{
   // Code that uses object
   // Your initialization needs to occur within the "using"
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
davidcahanAuthor Commented:
thanks...perfect
0
davidcahanAuthor Commented:
actually...along the same vein.  i have it working now EXCEPT for when I convert it to a memoryStream in order to make it searchable.  

looks like attached code below (look for // COPY STREAM TO MEMORY STREAM comment)
 string proxyUrl = url;
        HttpWebRequest webReq;
        HttpWebResponse webResp;
        bool success = false;
            webReq = (HttpWebRequest)WebRequest.Create(proxyUrl);
            webReq.Timeout = Convert.ToInt32(WebConfigurationManager.AppSettings["TimeOut"]);
            webResp = (HttpWebResponse)webReq.GetResponse();
            using (Stream streamHttp = webResp.GetResponseStream())
            {
            if (webResp.StatusCode == HttpStatusCode.OK)
            {
                success = true;
                //HttpContext.Current.Response.Write("OK");
                //HttpContext.Current.Response.End();
            }
        // Do not write anything if we failed the request. We may want to use old data
        // Watch for io errors. The file may be locked
        if (success)
        {
            HttpContext.Current.Application["OfflineCount"] = 0;    // Clear any flags when we were off line 
            String filePath = "";
           
                /* Begin XML validation */
                // COPY STREAM TO MEMORY STREAM
                streamHttp = copyToMemoryStream(streamHttp);
                if (!xmlIsValid(url, streamHttp, durationSeconds))
                {
                    schemReader.Close();
                    // Write to log when data is invalid
                    cimLog.WriteLog("\tFeed provider for feed: " + url + " returned invalid data.");
                    // Break out of function to ensure proxy does not cacher bad data
                    return;
                }
                schemReader.Close();
                // Reset position of streamHttp;
                streamHttp.Position = 0;
                try
                {
                    filePath = WebConfigurationManager.AppSettings["CachePath"].ToString() + cimHTTP.ConvertUrlToFileName(url);
                    FileStream streamCache = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                    BinaryWriter binCache = new BinaryWriter(streamCache);
                    int b;
                    while ((b = streamHttp.ReadByte()) != -1)
                    {
                        binCache.Write(Convert.ToByte(b));
                    }
                    binCache.Close();

                }
                catch (IOException ioError)
                {
                    cimLog.WriteLog("Could not write to " + filePath + ". " + ioError.Message, cimLog.LogType.Warning);
                }
                catch (Exception exError)
                {
                    cimLog.WriteLog(exError.Message);
                }
            }
        }


    private static MemoryStream copyToMemoryStream(Stream stream)
    {
        int b;
        MemoryStream memStream = new MemoryStream();
        while ((b = stream.ReadByte()) != -1)
        {
            memStream.WriteByte(Convert.ToByte(b));
        }
        memStream.Position = 0;
        return memStream;
    }

Open in new window

0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

käµfm³d 👽Commented:
Yes, that is because you are trying to assign to the using's variable, which can only be done within the "using" line. That is a point I didn't make clear in my last post...  my apologies  :)

You can think of a using variable as being constant/read only within that block. For your purposes, create a new, local stream variable that you can assign to and assign to it in line 25 of your last post. Something like:
    string proxyUrl = url;
    HttpWebRequest webReq;
    HttpWebResponse webResp;
    Stream tempStream;
    bool success = false;

    webReq = (HttpWebRequest)WebRequest.Create(proxyUrl);
    webReq.Timeout = Convert.ToInt32(WebConfigurationManager.AppSettings["TimeOut"]);
    webResp = (HttpWebResponse)webReq.GetResponse();

    using (Stream streamHttp = webResp.GetResponseStream())
    {
        if (webResp.StatusCode == HttpStatusCode.OK)
        {
            success = true;
            //HttpContext.Current.Response.Write("OK");
            //HttpContext.Current.Response.End();
        }

        // Do not write anything if we failed the request. We may want to use old data
        // Watch for io errors. The file may be locked
        if (success)
        {
            HttpContext.Current.Application["OfflineCount"] = 0;    // Clear any flags when we were off line 
            String filePath = "";

            /* Begin XML validation */
            // COPY STREAM TO MEMORY STREAM
            tempStream = copyToMemoryStream(streamHttp);

            if (!xmlIsValid(url, tempStream, durationSeconds))
            {
                schemReader.Close();
                // Write to log when data is invalid
                cimLog.WriteLog("\tFeed provider for feed: " + url + " returned invalid data.");
                // Break out of function to ensure proxy does not cacher bad data
                return;
            }
            schemReader.Close();
            // Reset position of streamHttp;
            streamHttp.Position = 0;

            try
            {
                filePath = WebConfigurationManager.AppSettings["CachePath"].ToString() + cimHTTP.ConvertUrlToFileName(url);
                FileStream streamCache = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                BinaryWriter binCache = new BinaryWriter(streamCache);
                int b;
                while ((b = streamHttp.ReadByte()) != -1)
                {
                    binCache.Write(Convert.ToByte(b));
                }
                binCache.Close();

            }
            catch (IOException ioError)
            {
                cimLog.WriteLog("Could not write to " + filePath + ". " + ioError.Message, cimLog.LogType.Warning);
            }
            catch (Exception exError)
            {
                cimLog.WriteLog(exError.Message);
            }
        }
    }
}

private static MemoryStream copyToMemoryStream(Stream stream)
{
    int b;
    MemoryStream memStream = new MemoryStream();
    while ((b = stream.ReadByte()) != -1)
    {
        memStream.WriteByte(Convert.ToByte(b));
    }
    memStream.Position = 0;
    return memStream;
}

Open in new window

0
davidcahanAuthor Commented:
yes...I should have both seen and already known that.  My apologies for the thickness of my head!!!!
0
käµfm³d 👽Commented:
No worries :)  Always glad to help!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.