本文整理汇总了C#中System.IO.StreamReader.Contains方法的典型用法代码示例。如果您正苦于以下问题:C# StreamReader.Contains方法的具体用法?C# StreamReader.Contains怎么用?C# StreamReader.Contains使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.StreamReader
的用法示例。
在下文中一共展示了StreamReader.Contains方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestMethod1
public void TestMethod1()
{
var web = new WebClient();
var stream = web.OpenRead("http://" + Environment.GetEnvironmentVariable("APPNAME"));
var result = new StreamReader(stream).ReadToEnd();
Assert.IsTrue(result.Contains("ASP.NET MVC Website") && result.Contains("Home"));
}
示例2: TestLoggingAndDelete
static void TestLoggingAndDelete(string path)
{
ILogger log = null;
try
{
log = new LoggerConfiguration()
.WriteTo.File(path)
.CreateLogger();
var message = Some.MessageTemplate();
log.Write(new LogEvent(
DateTimeOffset.Now,
LogEventLevel.Information,
null,
message,
Enumerable.Empty<LogEventProperty>()));
var refile = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var content = new StreamReader(refile).ReadToEnd();
refile.Dispose();
Assert.That(content.Contains(message.Text));
}
finally
{
var disposable = (IDisposable) log;
if (disposable != null) disposable.Dispose();
System.IO.File.Delete(path);
}
}
示例3: login
public bool login(string username, string password) {
var initialRequest = CyberghostRequest("https://account.cyberghostvpn.com/en_us/login");
var initialResponse = (HttpWebResponse)initialRequest.GetResponse();
var csrfToken = new StreamReader(initialResponse.GetResponseStream()).ReadToEnd();
csrfToken = csrfToken.Substring(csrfToken.IndexOf("var CSRF", StringComparison.Ordinal) + 12, 64);
var loginRequest = CyberghostRequest("https://account.cyberghostvpn.com/en_us/proxy/users/me?flags=17&csrf=" + csrfToken);
var postData = "username="+ username + "&authentication=" + password + "&captcha=";
var data = Encoding.ASCII.GetBytes(postData);
loginRequest.Method = "POST";
loginRequest.ContentType = "application/x-www-form-urlencoded";
loginRequest.ContentLength = data.Length;
using (var stream = loginRequest.GetRequestStream()) {
stream.Write(data, 0, data.Length);
}
try {
var loginResponse = (HttpWebResponse)loginRequest.GetResponse();
var responded = new StreamReader(loginResponse.GetResponseStream()).ReadToEnd();
return responded.Contains("user_name");
} catch (Exception) {
return false;
}
}
示例4: LoginToNicovideo
/// <summary>
/// 指定されたメールアドレスとパスワードでニコニコ動画にログインする.<para/>
/// アプリケーションの起動時に1回だけ呼ぶ.
/// </summary>
/// <param name="mail">メールアドレス</param>
/// <param name="passwd">パスワード</param>
public static void LoginToNicovideo(string mail, string passwd)
{
var req = (HttpWebRequest)HttpWebRequest.Create("https://secure.nicovideo.jp/secure/login?site=niconico");
req.Method = "POST";
var args = new Dictionary<string, string>
{
{"mail", mail},
{"password", passwd}
};
var s = args.Select(x => x.Key + "=" + x.Value).Aggregate((x, y) => x + "&" + y);
var bs = Encoding.UTF8.GetBytes(s);
req.ContentLength = bs.Length;
req.ContentType = "application/x-www-form-urlencoded";
req.CookieContainer = LoginCookie;
req.GetRequestStream().Write(bs, 0, bs.Length);
string result;
try {
var resp = (HttpWebResponse) req.GetResponse();
result = new StreamReader(resp.GetResponseStream()).ReadToEnd();
}
catch (Exception ex) {
throw new Exception("Error during login proccess.", ex);
}
if (result.Contains("wrongPass")) {
throw new Exception("Wrong ID or Password. Login Failed.");
}
}
示例5: TestLoggingAndDelete
static void TestLoggingAndDelete(string path)
{
ExecuteAndCleanUpFile(
path,
p => new LoggerConfiguration()
.WriteTo.File(p)
.CreateLogger(),
log =>
{
var message = Some.MessageTemplate();
log.Write(new LogEvent(
DateTimeOffset.Now,
LogEventLevel.Information,
null,
message,
Enumerable.Empty<LogEventProperty>()));
var refile = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var content = new StreamReader(refile).ReadToEnd();
refile.Dispose();
Assert.That(content.Contains(message.Text));
});
}
示例6: TryExtract
public bool TryExtract(string fullPath, Stream stream, string fileName, out ExtractionResult result)
{
result = null;
if (IsExtractable(fileName))
{
var encoding = GetFileEncoding(stream);
stream.Position = 0; //TODO: buscar una forma mas elegante de hacer esto
var text = new StreamReader(stream, encoding).ReadToEnd();
//TODO: mejorar este parche feo y caro para soportar a la vez ansi y utf sin bom
if (text.Contains("Ã"))
{
var bytes = encoding.GetBytes(text);
text = Encoding.UTF8.GetString(bytes);
}
result = new ExtractionResult()
{
ContentType = "text/plain",
PlainContent = text
};
return true;
}
else
{
return false;
}
}
示例7: WriterShouldNotIncludeTypeNameForCollectionOfDerivedType
public void WriterShouldNotIncludeTypeNameForCollectionOfDerivedType()
{
// JSON Light: writer doesn't include type name for collection of derived type
// If I have a collection property declared in metadata as Collection(Edm.Geography),
// and at serialization type, it's clearly a Collection(Edm.GeographyPoint),
// we won't write the type name for that property by default (i.e., minimal metadata mode).
var model = new EdmModel();
var entityType = new EdmEntityType("Var1", "Type");
entityType.AddKeys(entityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32));
entityType.AddProperty(new EdmStructuralProperty(entityType, "Geographies", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetSpatial(EdmPrimitiveTypeKind.Geography, false)))));
model.AddElement(entityType);
var writerSettings = new ODataMessageWriterSettings();
writerSettings.SetContentType(ODataFormat.Json);
writerSettings.DisableMessageStreamDisposal = true;
var message = new InMemoryMessage { Stream = new MemoryStream() };
using (ODataMessageWriter odataMessageWriter = new ODataMessageWriter((IODataRequestMessage)message, writerSettings, model))
{
ODataWriter odataWriter = odataMessageWriter.CreateODataEntryWriter();
odataWriter.WriteStart(
new ODataEntry
{
TypeName = "Var1.Type",
Properties = new[]
{
new ODataProperty()
{
Name = "Id",
Value = 1
},
new ODataProperty()
{
Name = "Geographies",
Value = new ODataCollectionValue
{
Items = new[]
{
GeographyPoint.Create(0,0),
GeographyPoint.Create(1,1),
GeographyPoint.Create(2,2)
}
}
},
}
});
odataWriter.WriteEnd();
odataWriter.Flush();
}
message.Stream.Position = 0;
var output = new StreamReader(message.Stream).ReadToEnd();
Assert.IsFalse(output.Contains("Collection(Edm.GeographyPoint)"), @"output.Contains(""Collection(Edm.GeographyPoint)"" == false");
}
示例8: Init
public static void Init()
{
try
{
GetResponse(WebRequest.Create(UpdateMsgPath), response => { UpdateMsg = new StreamReader(response.GetResponseStream()).ReadToEnd().ToString(); });
Core.DelayAction(
() =>
{
GetResponse(
WebRequest.Create(WebVersionPath),
response =>
{
var data = new StreamReader(response.GetResponseStream()).ReadToEnd().ToString();
if (data.Contains(CurrentVersionPath.ToString()))
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(DateTime.Now.ToString("[H:mm:ss - ") + "Info]" + " KappaAIO: Your version is Updated !");
Console.ResetColor();
}
else
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine(DateTime.Now.ToString("[H:mm:ss - ") + "Warn] KappaAIO: There is a new Update Available for KappaAIO !");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Cyan;
Chat.Print("<b>KappaAIO: There is a new Update Available for KappaAIO !</b>");
if (UpdateMsg != string.Empty)
{
Console.WriteLine(DateTime.Now.ToString("[H:mm:ss - ") + "Info] KappaAIO: " + UpdateMsg);
Console.ResetColor();
Chat.Print("<b>KappaAIO: " + UpdateMsg + "</b>");
Common.ShowNotification("There is a new Update Available for KappaAIO !", 10000, UpdateMsg);
}
else
{
Console.WriteLine(DateTime.Now.ToString("[H:mm:ss - ") + "Info] KappaAIO: Failed to retrive update msg");
Console.ResetColor();
Chat.Print("<b>KappaAIO: Failed to Retrieve Update msg</b>");
Common.ShowNotification("There is a new Update Available for KappaAIO !", 10000, "Failed to retrive update msg");
}
}
});
},
500);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine(DateTime.Now.ToString("[H:mm:ss - ") + "Warn] KappaAIO: Failed To Check for Updates !");
Console.WriteLine(DateTime.Now.ToString("[H:mm:ss - ") + ex);
Console.ResetColor();
}
}
示例9: TestRequest
public void TestRequest()
{
var request = new RestRequest(BaseUrl + "TestPage.aspx");
var response = request.Request("POST", "test=" + HttpUtility.UrlEncode("Bring the awesome."),
"application/x-www-form-urlencoded");
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, response.StatusDescription);
var responseBody = new StreamReader(response.GetResponseStream()).ReadToEnd();
Assert.IsTrue(responseBody.Contains("Bring the awesome."), responseBody);
}
示例10: GetAccessTokens
/// <summary>
/// Allows OAuth applications to directly exchange Twitter usernames and passwords for OAuth access tokens and secrets.
/// </summary>
/// <param name="consumerKey">The consumer key.</param>
/// <param name="consumerSecret">The consumer secret.</param>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
/// <returns>A <see cref="OAuthTokenResponse"/> instance.</returns>
public static OAuthTokenResponse GetAccessTokens(string consumerKey, string consumerSecret, string username, string password)
{
if (string.IsNullOrEmpty(consumerKey))
{
throw new ArgumentNullException("consumerKey");
}
if (string.IsNullOrEmpty(consumerSecret))
{
throw new ArgumentNullException("consumerSecret");
}
if (string.IsNullOrEmpty(username))
{
throw new ArgumentNullException("username");
}
if (string.IsNullOrEmpty(password))
{
throw new ArgumentNullException("password");
}
OAuthTokenResponse response = new OAuthTokenResponse();
try
{
WebRequestBuilder builder = new WebRequestBuilder(
new Uri("https://api.twitter.com/oauth/access_token"),
HTTPVerb.POST,
new OAuthTokens() { ConsumerKey = consumerKey, ConsumerSecret = consumerSecret },
"");
builder.Parameters.Add("x_auth_username", username);
builder.Parameters.Add("x_auth_password", password);
builder.Parameters.Add("x_auth_mode", "client_auth");
string responseBody = new StreamReader(builder.ExecuteRequest().GetResponseStream()).ReadToEnd();
response.Token = Regex.Match(responseBody, @"oauth_token=([^&]+)").Groups[1].Value;
response.TokenSecret = Regex.Match(responseBody, @"oauth_token_secret=([^&]+)").Groups[1].Value;
if (responseBody.Contains("user_id="))
response.UserId = long.Parse(Regex.Match(responseBody, @"user_id=([^&]+)").Groups[1].Value, CultureInfo.CurrentCulture);
response.ScreenName = Regex.Match(responseBody, @"screen_name=([^&]+)").Groups[1].Value;
}
catch (WebException wex)
{
throw new Exception(wex.Message, wex);
}
return response;
}
示例11: Serialize_message_without_typeinfo
public void Serialize_message_without_typeinfo()
{
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.Contains("$type"), result);
}
}
示例12: Should_be_able_to_serialize_and_deserialize_a_transport_message
public void Should_be_able_to_serialize_and_deserialize_a_transport_message()
{
var original = new TransportMessage();
var sut = SUT();
var stream = sut.Serialize(original);
var xml = new StreamReader(stream).ReadToEnd();
Assert.IsTrue(xml.Contains(original.MessageId.ToString()));
stream.Position = 0;
Assert.AreEqual(original.MessageId, ((TransportMessage)sut.Deserialize(typeof(TransportMessage), stream)).MessageId);
}
示例13: Login
public static Tuple<bool, string> Login(string user, string hash)
{
if (user == null || hash == null)
{
return new Tuple<bool, string>(false, "Password or username is empty");
}
try
{
var uri = "username=" + WebUtility.UrlEncode(user) + "&password=" + hash;
var dataBytes = Encoding.UTF8.GetBytes(uri);
var wr = WebRequest.Create("http://" + AuthServer + "/forum/api.php?request=login");
wr.Timeout = 2000;
wr.ContentLength = dataBytes.Length;
wr.Method = "POST";
wr.ContentType = "application/x-www-form-urlencoded";
var dataStream = wr.GetRequestStream();
dataStream.Write(dataBytes, 0, dataBytes.Length);
dataStream.Close();
var response = wr.GetResponse();
using (var stream = response.GetResponseStream())
{
if (stream != null)
{
var responseString = new StreamReader(stream, Encoding.UTF8).ReadToEnd();
if (responseString.Contains("success"))
{
return new Tuple<bool, string>(true, "Success!");
}
}
}
return new Tuple<bool, string>(false, "Wrong password or username, register at http://" + AuthServer);
}
catch (Exception e)
{
return new Tuple<bool, string>(true, "Fallback T_T");
}
}
示例14: ThenAllDataWillBeSent
public void ThenAllDataWillBeSent()
{
GivenKinesisClient();
WhenLoggerCreated();
var messages = Fixture.CreateMany<string>(100).ToList();
foreach (var message in messages)
{
Logger.Information(message);
Thread.Sleep(TimeSpan.FromMilliseconds(ThrottleTime.TotalMilliseconds / 30));
}
Thread.Sleep(ThrottleTime.Add(ThrottleTime));
DataSent.Position = 0;
var data = new StreamReader(DataSent).ReadToEnd();
messages.ShouldAllBe(msg => data.Contains(msg));
}
示例15: Serialize_message_without_concrete_implementation
public void Serialize_message_without_concrete_implementation()
{
var messageMapper = new MessageMapper();
messageMapper.Initialize(new[]
{
typeof(ISuperMessageWithoutConcreteImpl)
});
var serializer = new JsonMessageSerializer(messageMapper);
using (var stream = new MemoryStream())
{
serializer.Serialize(messageMapper.CreateInstance<ISuperMessageWithoutConcreteImpl>(), stream);
stream.Position = 0;
var result = new StreamReader(stream).ReadToEnd();
Assert.That(!result.Contains("$type"), result);
Assert.That(result.Contains("SomeProperty"), result);
}
}