I tried calling Extension method defined under static class from Main(), It worked. Now I want to use this in my application, to do so I need make the Extension method as a static method(Because I don' t have static classes defined in my application) and call It from Main().
Here what I' m trying:
public class Get
{
public static void CopyTo(Stream input, Stream output) //Method
{
byte[] buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write (buffer, 0, read);
}
}
public static void Main ()
{
////I' m just mentioning a small part of my code
////Please ignore about the variables(url, baseURL,authenticatestr...) those are not declared here, they have been declared at some other part in the code
/////Here in the main method I have a call to the above method
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
request = (HttpWebRequest)WebRequest.Create (baseURL + uri);
request.Headers.Add ("Authn", authenticateStr);
request.Accept = "";
request.Method = "GET";
webResponse = (HttpWebResponse)request.GetResponse();
using (MemoryStream ms = new MemoryStream())
using (FileStream outfile = new FileStream("1" , FileMode.Create)) {
webResponse.GetResponseStream().CopyTo(ms);///Here I need to call my method
outfile.Write(ms.GetBuffer(), 0, (int)ms.Length);
}
But this is still trying to call the .NetFramework CopyTo() method. How do I make a call to the defined method int the code? Please help me.
Thank you.
How do I make a call to the defined method int the code?
Just don't call it on a stream (which makes it look like an instance method). Call it as a normal static method, with two arguments corresponding to the two parameters:
CopyTo(webResponse.GetResponseStream(), ms);
Non-extension static methods can never be called on an instance. You can use just the simple name, or qualify it with the type name ( Get.CopyTo(...)
).
It's not clear why you want to use this at all if you're using .NET 4+ where CopyTo
is supported though.
If I understood your question right, you wanted to create an extension method which copies a stream into another one. To define an extension method, use
public static class myExtensions
{
public static void myCopyTo(this Stream input, Stream output)
{
// your code goes here
}
}
Then you can call it the following way:
webResponse.GetResponseStream().myCopyTo(ms);
Notes:
this
as 1st parameter. This parameter denotes the type of the class which you want to extend. CopyTo
method I hope that helps. Please let me know if you need any additional hints.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.