本文整理汇总了C#中System.IO.StreamReader.StartsWith方法的典型用法代码示例。如果您正苦于以下问题:C# StreamReader.StartsWith方法的具体用法?C# StreamReader.StartsWith怎么用?C# StreamReader.StartsWith使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.StreamReader
的用法示例。
在下文中一共展示了StreamReader.StartsWith方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetAutoDocumentationDerived
public void GetAutoDocumentationDerived()
{
WebRequest req = WebRequest.Create("http://127.0.0.1:11001/");
Stream stm = req.GetResponse().GetResponseStream();
string doc = new StreamReader(stm).ReadToEnd();
Assert.IsNotNull(doc);
Assert.IsTrue(doc.StartsWith("<html>"));
}
示例2: WeiboShortUrl
public async Task<string> WeiboShortUrl(string url) {
var wsuRequest = WebRequest.Create("http://weibo.com/aj/mblog/video?_wv=5&url=" + url) as HttpWebRequest;
if (wsuRequest == null)
return string.Empty;// ignore file
wsuRequest.UserAgent = userAgent;
InjectWeiboCookie(wsuRequest);
try {
using (var wsuResponse = await wsuRequest.GetResponseAsync() as HttpWebResponse) {
if (wsuResponse.StatusCode != HttpStatusCode.OK)
return string.Empty;
string responseData = new StreamReader(wsuResponse.GetResponseStream()).ReadToEnd();
if (responseData.StartsWith("<!DOCTYPE"))
return "sorry,系统出现错误,请稍后再试。";
var wsuObj = JsonConvert.DeserializeObject<WeiboShartUrlResponse>(responseData);
return wsuObj.data.url;
}
} catch (Exception) {
return string.Empty;
}
}
示例3: CreateRequest
public static object CreateRequest(string operationName, string httpMethod, NameValueCollection queryString, NameValueCollection requestForm, Stream inputStream)
{
var operationType = EndpointHost.ServiceOperations.GetOperationType(operationName);
AssertOperationExists(operationName, operationType);
if (httpMethod == "GET" || httpMethod == "OPTIONS")
{
try
{
return KeyValueDataContractDeserializer.Instance.Parse(queryString, operationType);
}
catch (Exception ex)
{
var log = EndpointHost.Config.LogFactory.GetLogger(typeof(JsvHandlerBase));
log.ErrorFormat("Could not deserialize '{0}' request using KeyValueDataContractDeserializer: '{1}' '{2}'",
operationType, queryString, ex);
throw;
}
}
var formData = new StreamReader(inputStream).ReadToEnd();
var isJsv = formData.StartsWith("{");
try
{
return isJsv ? TypeSerializer.DeserializeFromString(formData, operationType)
: KeyValueDataContractDeserializer.Instance.Parse(requestForm, operationType);
}
catch (Exception ex)
{
var log = EndpointHost.Config.LogFactory.GetLogger(typeof(JsvHandlerBase));
var deserializer = isJsv ? "TypeSerializer" : "KeyValueDataContractDeserializer";
log.ErrorFormat("Could not deserialize '{0}' request using {1}: '{2}'\nError: {3}",
operationType, deserializer, formData, ex);
throw;
}
}
示例4: Program
Program()
{
System.Timers.Timer t = new System.Timers.Timer(5000);
t.AutoReset = true;
t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
t.Start();
Thread connect = new Thread(new ThreadStart(connectThread));
connect.IsBackground = true;
connect.Start();
TcpListener server = new TcpListener(IPAddress.Loopback, 8003);
server.Start();
d("listening on :8003");
while (true) {
TcpClient cli = server.AcceptTcpClient();
string input = new StreamReader(cli.GetStream()).ReadLine();
d("RX: " + input);
if (input.StartsWith("flash ")) {
sendNotify("flash on");
}
cli.Close();
}
}
示例5: LoadObjFile
/// <summary>
/// http://en.wikipedia.org/wiki/Wavefront_.obj_file
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static Mesh LoadObjFile(string filename)
{
var file = Filepaths.GetModelFileInfo(filename);
if (!file.Exists)
throw new ModelException(StandardExceptions.NewFileNotFound(file));
string src;
using (var s = new StreamReader(file.FullName))
{
src = s.ReadToEnd();
}
var lines = src.Split('\n').Where(s => !s.StartsWith("#")).ToList();
var vertexs = new List<Vector3>();
var vertexTextures = new List<Vector2>();
var vertexNormals = new List<Vector3>();
foreach (
var xyzw in
lines.Where(s => s.StartsWith("v "))
.Select(s => s.Substring(s.IndexOf(' ') + 1).Split(' '))
.ToList())
{
string x = "", y = "", z = "", w = "";
if (xyzw.Length >= 1)
x = xyzw[0];
if (xyzw.Length >= 2)
y = xyzw[1];
if (xyzw.Length >= 3)
z = xyzw[2];
if (xyzw.Length == 4)
w = xyzw[3];
// TODO: Vertex4 for position in the Vertex class
vertexs.Add(new Vector3(float.Parse(x), float.Parse(y), float.Parse(z)));
}
// TODO: .mtl and that stuff
foreach (
var uvw in
lines.Where(s => s.StartsWith("vt "))
.Select(s => s.Substring(s.IndexOf(' ') + 1).Split(' '))
.ToList())
{
string u = "", v = "", w = "";
if (uvw.Length >= 1)
u = uvw[0];
if (uvw.Length >= 2)
v = uvw[1];
if (uvw.Length == 3)
w = uvw[3];
// TODO: Vertex3 for texture in the Vertex class
vertexTextures.Add(new Vector2(float.Parse(u), float.Parse(v)));
}
foreach (
var xyz in
lines.Where(s => s.StartsWith("vn "))
.Select(s => s.Substring(s.IndexOf(' ') + 1).Split(' '))
.ToList())
{
string x = "", y = "", z = "";
if (xyz.Length >= 1)
x = xyz[0];
if (xyz.Length >= 2)
y = xyz[1];
if (xyz.Length >= 3)
z = xyz[2];
vertexNormals.Add(new Vector3(float.Parse(x), float.Parse(y), float.Parse(z)).Normalized());
}
// TODO: lines starting with vp
var vertices = new List<Vertex>();
var indices = new List<int>();
foreach (
var face in
lines.Where(s => s.StartsWith("f "))
.Select(s => s.Substring(s.IndexOf(' ') + 1).Split(' '))
.ToList())
{
for (int i = 0; i < face.Length - 2; i++)
{
for (int j = 0; j < 3; j++)
{
string[] vert = face[i + j].Split('/');
int v = 0, t = 0, n = 0;
v = int.Parse(vert[0]);
if (vert.Length >= 2 && vert[1] != string.Empty)
t = int.Parse(vert[1]);
if (vert.Length == 3)
n = int.Parse(vert[2]);
Vector3 position = vertexs[v - 1];
Vector2 texture = Vector2.Zero;
//.........这里部分代码省略.........
示例6: Serialize_message_without_wrapping
public void Serialize_message_without_wrapping()
{
var messageMapper = new MessageMapper();
var serializer = new JsonMessageSerializer(messageMapper);
using (var stream = new MemoryStream())
{
serializer.Serialize(new SimpleMessage(), stream);
stream.Position = 0;
var result = new StreamReader(stream).ReadToEnd();
Assert.That(!result.StartsWith("["), result);
}
}
示例7: UploadFile
// upload a file using the MediaWiki upload API
private void UploadFile(string editToken, LoginInfo loginInfo, string localFilePath, string remoteFilename)
{
UploadFile[] files = new UploadFile[] { new UploadFile(localFilePath, "file", "application/octet-stream") };
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GetApiUrl());
request.CookieContainer = loginInfo.Cookies;
var parameters = new System.Collections.Specialized.NameValueCollection();
parameters["format"] = "xml";
parameters["action"] = "upload";
parameters["filename"] = Path.GetFileName(localFilePath);
parameters["token"] = editToken;
var response = HttpUploadHelper.Upload(request, files, parameters);
string strResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
if (strResponse.StartsWith("unknown_action"))
{
// fallback : upload using web form
UploadFileThroughForm(loginInfo, localFilePath, remoteFilename);
return;
}
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strResponse);
var element = xmlDoc.GetElementsByTagName("api")[0].ChildNodes[0];
if (element.Name == "error")
{
string errorCode = element.Attributes["code"].Value;
string errorMessage = element.Attributes["info"].Value;
throw new MediaWikiException("Error uploading to MediaWiki: " + errorCode + "\r\n" + errorMessage);
}
string result = element.Attributes["result"].Value;
if (result == "Warning")
{
foreach (XmlNode child in element.ChildNodes)
{
if (child.Name == "warnings")
{
if (child.Attributes["exists"] != null)
{
string existingImageName = child.Attributes["exists"].Value;
throw new MediaWikiException("Image already exists on the wiki: " + existingImageName);
}
}
}
}
if (result != "Success")
throw new MediaWikiException("Error uploading to MediaWiki:\r\n" + result);
}
catch (XmlException)
{
throw new MediaWikiException("Unexpected answer while uploading:\r\n" + strResponse);
}
}
示例8: Login1
// login
private LoginInfo Login1(LoginInfo loginInfo)
{
string postData = string.Format("format=xml&action=login&lgname={0}&lgpassword={1}", Options.Account.Username, Options.Account.Password);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] postBytes = encoding.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GetApiUrl());
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
request.AllowAutoRedirect = true;
var cookieContainer = loginInfo.Cookies ?? new CookieContainer();
request.CookieContainer = cookieContainer;
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
var response = request.GetResponse();
string strResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
// redirected to another page
if (strResponse.StartsWith("<!DOCTYPE html"))
{
if (loginInfo.Redirected)
{
throw new MediaWikiException("Still could not log in after redirection");
}
var uri = response.ResponseUri;
LoginInfo newLoginInfo = LoginRedirected(uri);
return Login1(newLoginInfo);
}
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strResponse);
var loginElement = xmlDoc.GetElementsByTagName("api")[0].ChildNodes[0];
string result = loginElement.Attributes["result"].Value;
string token = (loginElement.Attributes["token"] ?? loginElement.Attributes["lgtoken"]).Value;
bool needToken;
if (result == "Success")
needToken = false;
else if (result == "NeedToken")
needToken = true;
else
{
HandleError(result);
// should not happen since HandleError always throws an exception
throw new Exception("Error not handled");
}
return new LoginInfo() { Token = token, Cookies = cookieContainer, NeedToken = needToken };
}
catch (XmlException)
{
throw new MediaWikiException("unexpected answer:\r\n" + strResponse);
}
}
示例9: Connect
/// <summary>
/// Log in using a username and password. You need a secret as well for this to work
/// because you cannot get the login form without the hash. I guess i could use a random account
/// hash so that the paramater isn't required, but will leave it there for now.
/// </summary>
/// <param name="DogeDice">If set to true, Site will connect to DogeDice, otherwise to Just-Dice</param>
/// <param name="Username">username to log in with. Case sensitive</param>
/// <param name="Password">Password to log in with. Case sensitive</param>
/// <param name="GACode">Google Auth code.</param>
/// <param name="secretHash">Hash from the hash cookie</param>
/// <returns></returns>
public bool Connect(bool DogeDice, string Username, string Password, string GACode)
{
xhrval = "";
privatehash = (!DogeDice) ? "0f3aa87b64103349a9cabcccbb312e606e9013c3eee8f364b9ee4e91ad2c67d3" : "0fc4126d7045e16c05d18b6fda82324c2f987ac7f51317f317d6488680a37668";
host = "https://" + ((DogeDice) ? "doge" : "just") + "-dice.com";
request = (HttpWebRequest)HttpWebRequest.Create(host);
sUsername = Username;
sPassword = Password;
bool _Connected = getInitalHeaders();
string Message = string.Format("username={0}&password={1}&code={2}", Username, Password, GACode);
var tmprequest = (HttpWebRequest)HttpWebRequest.Create(host);
if (Proxy != null)
tmprequest.Proxy = Proxy;
tmprequest.ContentType = "application/x-www-form-urlencoded";
tmprequest.ContentLength = Message.Length;
tmprequest.Referer = host;
tmprequest.CookieContainer = request.CookieContainer;
tmprequest.Method = "POST";
tmprequest.UserAgent = "JDCAPI - " + UserAgent;
using (var writer = new StreamWriter(tmprequest.GetRequestStream()))
{
string writestring = Message as string;
writer.Write(writestring);
}
HttpWebResponse EmitResponse = (HttpWebResponse)tmprequest.GetResponse();
string sEmitResponse = new StreamReader(EmitResponse.GetResponseStream()).ReadToEnd();
if (OnLoginError != null && sEmitResponse.StartsWith("<!DOCTYPE html><html lang=\"en\"><head><script src=\"/javascripts/jquery-1.10.0.min.js\">"))
{
OnLoginError("Incorrect Password");
_Connected = false;
}
getxhrval();
int counter = 0;
while (!gotinit && _Connected)
{
if (counter++ > 4)
_Connected = false;
GetInfo();
}
if (_Connected)
{
active = true;
Thread poll = new Thread(new ThreadStart(pollingLoop));
poll.Start();
Connected = true;
if (this.LoginEnd != null)
{
this.LoginEnd(Connected);
}
return Connected;
}
else
{
Connected = false;
if (this.LoginEnd != null)
{
this.LoginEnd(Connected);
}
return Connected;
}
}
示例10: getInitalHeaders
/// <summary>
/// gets the inital cookies for the connections.
/// cookies includeL __cfduid, connect.sid, hash. These are required for mainting the same connection
/// </summary>
private bool getInitalHeaders()
{
string sResponse = "";
request = (HttpWebRequest)HttpWebRequest.Create(host);
if (Proxy != null)
request.Proxy = Proxy;
var cookies = new CookieContainer();
request.CookieContainer = cookies;
request.UserAgent = "JDCAPI - " + UserAgent;
if (!string.IsNullOrEmpty(privatehash))
{
request.CookieContainer.Add(new Cookie("hash", privatehash, "/", (host.Contains("just")) ? ".just-dice.com" : ".doge-dice.com"));
}
//request.CookieContainer.Add(new Cookie("cf_clearance", "bc22bf9b9733912f976dc28c78796fc91e19b7fe-1393330223-86400", "/", ".just-dice.com"));
HttpWebResponse Response = null;
try
{
Response = (HttpWebResponse)request.GetResponse();
}
catch (WebException e)
{
if (logging)
writelog(e.Message);
if (e.Response != null)
{
Response = (HttpWebResponse)e.Response;
string s1 = new StreamReader(Response.GetResponseStream()).ReadToEnd();
string tmp = s1.Substring(s1.IndexOf("var t,r,a,f,"));
string varfirst = tmp.Substring("var t,r,a,f,".Length + 1, tmp.IndexOf("=") - "var t,r,a,f,".Length - 1);
string varsec = tmp.Substring(tmp.IndexOf("{\"") + 2, tmp.IndexOf("\"", tmp.IndexOf("{\"") + 3) - tmp.IndexOf("{\"") - 2);
string var = varfirst + "." + varsec;
string varline = "var " + tmp.Substring("var t,r,a,f,".Length + 1, tmp.IndexOf(";") - "var t,r,a,f,".Length);
string initbval = tmp.Substring(tmp.IndexOf(":+") + 1, tmp.IndexOf("))") + 3 - tmp.IndexOf(":+") - 1);
string vallist = tmp.Substring(tmp.IndexOf(var), tmp.IndexOf("a.value") - tmp.IndexOf(var));
string script = varline + vallist;
object Result = 0;
try
{
Result = ScriptEngine.Eval("jscript", script);
}
catch (Exception ex)
{
}
int aval = int.Parse(Result.ToString(), System.Globalization.CultureInfo.InvariantCulture);
string jschl_vc = s1.Substring(s1.IndexOf(" name=\"jschl_vc\" value=\""));
jschl_vc = jschl_vc.Substring(("name=\"jschl_vc\" value=\"").Length + 1);
int len = jschl_vc.IndexOf("\"/>\n");
jschl_vc = jschl_vc.Substring(0, len);
try
{
//string content = new WebClient().DownloadString("cdn-cgi/l/chk_jschl?jschl_vc=1bb30f6e73b41c8dd914ccbf64576147&jschl_answer=84");
CookieContainer cookies2 = request.CookieContainer;
string req = string.Format(host + "/cdn-cgi/l/chk_jschl?jschl_vc={0}&jschl_answer={1}", jschl_vc, aval + 13);
request = (HttpWebRequest)HttpWebRequest.Create(req);
if (Proxy != null)
request.Proxy = Proxy;
request.UserAgent = "JDCAPI - " + UserAgent;
request.CookieContainer = cookies2;
Response = (HttpWebResponse)request.GetResponse();
}
catch
{
return false;
}
}
else
{
Connected = false;
return false;
}
}
string s = new StreamReader(Response.GetResponseStream()).ReadToEnd();
if (s.StartsWith("<!DOCTYPE html><html lang=\"en\"><head><script src=\"/javascripts/jquery-1.10.0.min.js\">"))
{
if (OnLoginError != null && sUsername == "" && sPassword == "")
{
OnLoginError("This account requires a username and password");
Connected = false;
return false;
}
}
foreach (Cookie cookievalue in Response.Cookies)
{
request.CookieContainer.Add(cookievalue);
switch (cookievalue.Name)
{
case "connect.sid": conid = cookievalue.Value; break;
case "__cfduid": id = cookievalue.Value; break;
//.........这里部分代码省略.........
示例11: WhiteSpaceShouldBeIncludedWhenRequired
public void WhiteSpaceShouldBeIncludedWhenRequired()
{
var mockSender = A.Fake<IMailSender>();
var attribute = new SmtpMailAttributes();
var mailer = new TestMailerBase(attribute, mockSender);
var email = mailer.Email("WhitespaceTrimTest", false);
var body = new StreamReader(email.Mail.AlternateViews[0].ContentStream).ReadToEnd();
Assert.True(body.StartsWith(Environment.NewLine));
Assert.True(body.EndsWith(Environment.NewLine));
}
示例12: Serialize_message_without_wrapping
public void Serialize_message_without_wrapping()
{
using (var stream = new MemoryStream())
{
Serializer.SkipArrayWrappingForSingleMessages = true;
Serializer.Serialize(new object[] { new SimpleMessage() }, stream);
stream.Position = 0;
var result = new StreamReader(stream).ReadToEnd();
Assert.That(!result.StartsWith("["), result);
}
}
示例13: DesDecode
public static string DesDecode(string Source, byte[] RegKey, byte[] RegIV)
{
string text = "#$%!#^!#$^[email protected]#%@#[email protected]%!#45";
byte[] rgbIV = new byte[] { 0x7b, 0x20, 0x29, 0x91, 0xee, 0x86, 0x34, 0xe3, 0xc0, 0xca, 0x62, 0xdf, 0x66, 0xe4, 15, 0xd1 };
if (RegKey != null)
{
rgbIV = RegKey;
}
byte[] rgbKey = new byte[] { 0x8a, 0xc0, 0x57, 50, 2, 0xb9, 0x59, 0x81, 0xd6, 0x98, 0xce, 0xfe, 0x6f, 0xe5, 0x31, 0x9c };
if (RegIV != null)
{
rgbKey = RegIV;
}
int num = Source.Length / 2;
byte[] bytes = new byte[num];
int index = 0;
for (int i = 0; i < Source.Length; i++)
{
int num2 = Uri.FromHex(Uri.HexUnescape(Source, ref index));
i++;
num2 = (num2 * 0x10) + Uri.FromHex(Uri.HexUnescape(Source, ref index));
bytes[i / 2] = Convert.ToByte(num2);
}
Source = Encoding.Unicode.GetString(bytes, 0, bytes.Length);
byte[] buffer = new UnicodeEncoding().GetBytes(Source);
MemoryStream stream = new MemoryStream(buffer, 0, buffer.Length);
ICryptoTransform transform = new TripleDESCryptoServiceProvider().CreateDecryptor(rgbKey, rgbIV);
CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Read);
string text3 = new StreamReader(stream2, new UnicodeEncoding()).ReadToEnd();
stream.Close();
stream2.Close();
if (!text3.StartsWith(text))
{
throw new Exception("bad source");
}
return text3.Substring(text.Length);
}
示例14: BindModel
public override object BindModel( ControllerContext controllerContext, ModelBindingContext bindingContext )
{
if ( EhRequisicaoJson( controllerContext ) )
{
string jsonData = new StreamReader( controllerContext.RequestContext.HttpContext.Request.InputStream ).ReadToEnd();
if ( jsonData.StartsWith( Root ) )
{
jsonData = jsonData.Replace( Root, "" );
jsonData = jsonData.Substring( 0, jsonData.Length - 1 );
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Deserialize( jsonData, bindingContext.ModelMetadata.ModelType );
}
return base.BindModel( controllerContext, bindingContext );
}