当前位置: 首页>>代码示例>>C#>>正文


C# StreamReader.Substring方法代码示例

本文整理汇总了C#中System.IO.StreamReader.Substring方法的典型用法代码示例。如果您正苦于以下问题:C# StreamReader.Substring方法的具体用法?C# StreamReader.Substring怎么用?C# StreamReader.Substring使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.IO.StreamReader的用法示例。


在下文中一共展示了StreamReader.Substring方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: RaygunRequestMessage

        public RaygunRequestMessage(HttpContext context)
        {
            HostName = context.Request.Url.Host;
              Url = context.Request.Url.AbsolutePath;
              HttpMethod = context.Request.RequestType;
              IPAddress = context.Request.UserHostAddress;
              Data = ToDictionary(context.Request.ServerVariables);
              QueryString = ToDictionary(context.Request.QueryString);
              Headers = ToDictionary(context.Request.Headers);
              Form = ToDictionary(context.Request.Form, true);

              try
              {
            var contentType = context.Request.Headers["Content-Type"];
            if (contentType != "text/html" && contentType != "application/x-www-form-urlencoded" && context.Request.RequestType != "GET")
            {
              int length = 4096;
              string temp = new StreamReader(context.Request.InputStream).ReadToEnd();
              if (length > temp.Length)
              {
            length = temp.Length;
              }

              RawData = temp.Substring(0, length);
            }
              }
              catch (HttpException)
              {
              }
        }
开发者ID:modulexcite,项目名称:raygun4net,代码行数:30,代码来源:RaygunRequestMessage.cs

示例2: GetTranslatedText

        public string GetTranslatedText(string sourseText, string langSource, string langTrans)
        {
            Helper helper = new Helper();
            string returnValue = string.Empty;

            if (!helper.IsNullOrEmpty(sourseText))
            {
                HttpWebRequest request = null;
                HttpWebResponse response = null;
                StringBuilder builder = new StringBuilder("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0");
                builder.Append("&q=" + HttpUtility.UrlEncode(sourseText.Trim()));
                builder.Append("&langpair=" + langSource + "|" + langTrans);
                builder.Append("&key=" + ConfigurationManager.AppSettings["GoogleAPIKey"]);
                request = (HttpWebRequest)WebRequest.Create(builder.ToString());
                request.Method = NHttpMethod.GET.ToString();
                response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    string str = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    string leadingText = "{\"translatedText\":\"";
                    int startIndex = str.IndexOf(leadingText) + leadingText.Length;
                    int index = str.IndexOf("\"},");

                    returnValue = str.Substring(startIndex, index - startIndex);
                }
                else
                    returnValue = "Google translation service no response.";
            }

            return returnValue;
        }
开发者ID:wjkong,项目名称:MicNets,代码行数:32,代码来源:AjaxWS.asmx.cs

示例3: GetDownloadUrls

        /// <summary>
        /// Gets a list of <see cref="VideoInfo"/>s for the specified URL.
        /// </summary>
        /// <param name="videoUrl">The URL of the YouTube video.</param>
        /// <returns>A list of <see cref="VideoInfo"/>s that can be used to download the video.</returns>
        /// <exception cref="ArgumentException">videoUrl is not a valid YouTube URL.</exception>
        /// <exception cref="WebException">An error occured while downloading the video infos.</exception>
        public static IEnumerable<VideoInfo> GetDownloadUrls(string videoUrl)
        {
            videoUrl = NormalizeYoutubeUrl(videoUrl);

            const string startConfig = "yt.playerConfig = ";

            string pageSource;

            var req = WebRequest.Create(videoUrl);

            using (var resp = req.GetResponse())
            {
                pageSource = new StreamReader(resp.GetResponseStream(), Encoding.UTF8).ReadToEnd();
            }

            string videoTitle = GetVideoTitle(pageSource);

            int playerConfigIndex = pageSource.IndexOf(startConfig, StringComparison.Ordinal);

            if (playerConfigIndex > -1)
            {
                string signature = pageSource.Substring(playerConfigIndex);
                int endOfJsonIndex = signature.TrimEnd(' ').IndexOf("yt.setConfig", StringComparison.Ordinal);
                signature = signature.Substring(startConfig.Length, endOfJsonIndex - 26);

                JObject playerConfig = JObject.Parse(signature);
                JObject playerArgs = JObject.Parse(playerConfig["args"].ToString());
                var availableFormats = (string)playerArgs["url_encoded_fmt_stream_map"];

                const string argument = "url=";
                const string endOfQueryString = "&quality";

                if (availableFormats != String.Empty)
                {
                    var urlList = new List<string>(Regex.Split(availableFormats, argument));

                    var downLoadInfos = new List<VideoInfo>();

                    // Format the URL
                    var urls = urlList
                        .Where(entry => !String.IsNullOrEmpty(entry.Trim()))
                        .Select(entry => entry.Substring(0, entry.IndexOf(endOfQueryString, StringComparison.Ordinal)))
                        .Select(entry => new Uri(Uri.UnescapeDataString(entry)));

                    foreach (Uri url in urls)
                    {
                        NameValueCollection queryString = HttpUtility.ParseQueryString(url.Query);

                        // for this version, only get the download URL
                        byte formatCode = Byte.Parse(queryString["itag"]);
                        // Currently based on youtube specifications (later we'll depend on the MIME type returned from the web request)
                        downLoadInfos.Add(new VideoInfo(url.ToString(), videoTitle, formatCode));
                    }

                    return downLoadInfos;
                }
            }

            return Enumerable.Empty<VideoInfo>();
        }
开发者ID:random-username,项目名称:YoutubeExtractor,代码行数:67,代码来源:DownloadUrlResolver.cs

示例4: 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;
            }
            
        }
开发者ID:josh-richardson,项目名称:cyberghosty,代码行数:28,代码来源:CyberGhostInstance.cs

示例5: Main

        public void Main(string[] args)
        {
            foreach (var kvp in _pathToResource)
            {
                var success = true;
                var fileContent = new StreamReader(new FileStream(kvp.Key, FileMode.Open)).ReadToEnd();
                var resourceContent = new StreamReader(_assembly.GetManifestResourceStream(kvp.Value)).ReadToEnd();
                if (fileContent.Length > resourceContent.Length)
                {
                    success = false;
                    Console.WriteLine($"{ kvp.Key } is { fileContent.Length - resourceContent.Length } chars longer than { kvp.Value }.");
                    Console.WriteLine($"\tFile ends with     '...{ fileContent.Substring(fileContent.Length - 20) }'.");
                    Console.WriteLine($"\tResource ends with '...{ resourceContent.Substring(resourceContent.Length - 20) }'.");
                }
                else if (fileContent.Length < resourceContent.Length)
                {
                    success = false;
                    Console.WriteLine($"{ kvp.Key } is { resourceContent.Length - fileContent.Length } chars shorter than { kvp.Value }.");
                    Console.WriteLine($"\tFile ends with     '...{ fileContent.Substring(fileContent.Length - 20) }'.");
                    Console.WriteLine($"\tResource ends with '...{ resourceContent.Substring(resourceContent.Length - 20) }'.");
                }
                else
                {
                    for (var i = 0; i < fileContent.Length; i++)
                    {
                        if (fileContent[i] != resourceContent[i])
                        {
                            success = false;

                            var length = (i + 20 > fileContent.Length) ? fileContent.Length - i : 20;
                            Console.WriteLine($"Mismatch at index '{ i }' in { kvp.Key }.");
                            Console.WriteLine($"\tFile contains     '...{ fileContent.Substring(i, length) }'.");
                            Console.WriteLine($"\tResource contains '...{ resourceContent.Substring(i, length) }'.");
                            break;
                        }
                    }
                }

                if (success)
                {
                    Console.WriteLine($"Success for { kvp.Key }.");
                }
            }
        }
开发者ID:dougbu,项目名称:LargeResources,代码行数:44,代码来源:Program.cs

示例6: write

        public void write(string data)
        {

            Request.InputStream.Seek(0, SeekOrigin.Begin);
            string jsonData = new StreamReader(Request.InputStream).ReadToEnd();
            String subject = jsonData.Split('<')[0];
            int subjectId = Int32.Parse(subject);
            String xaml = jsonData.Substring(subject.Length);
      
            _db.WS_Subjects.Find(subjectId).Xaml_Data = xaml;
           _db.SaveChanges();
        }
开发者ID:InFlowBPM,项目名称:InFlow-BPMS,代码行数:12,代码来源:XAMLController.cs

示例7: GetAcceptCallback

        /*
         * Gets a response from the /tribunal/accept request. This response will contain
         * the case id and the number of game in the case.
         * These two pieces of info are used by the CaseLoader class to request the JSON data.
         */
        private void GetAcceptCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
            String html = new StreamReader(response.GetResponseStream()).ReadToEnd();
            //System.Diagnostics.Debug.WriteLine("Number of Cookies after: " + MobileTribunal.Instance.cookies.Count);
            //System.Diagnostics.Debug.WriteLine("Response: " + (int)response.StatusCode);
            //System.Diagnostics.Debug.WriteLine("Length: " + html.Length + "\nTitle: " + html.Substring(html.IndexOf("<title>")));

            /* The case id will be found in the title of the page
             * it will look something like: <title>The Tribunal -  Reviewing Case CASEID</title>
             */
            String caseId;
            int numGames;
            int startIndex = html.IndexOf("Reviewing Case ") + "Reviewing Case ".Length;
            caseId = html.Substring(startIndex, html.IndexOf("</title>") - startIndex);
            System.Diagnostics.Debug.WriteLine("Case Id: " + caseId);

            /* The number of games is stored in a JSON structure.
             * it looks something like 'game_count': NUMGAMES,
             */
            startIndex = html.IndexOf("'game_count': ") + "'game_count': ".Length;
            bool gotNumGames = int.TryParse(html.Substring(startIndex, html.IndexOf(",", startIndex) - startIndex), out numGames);
            System.Diagnostics.Debug.WriteLine("Number of games: " + numGames);

            if (gotNumGames && !(String.IsNullOrEmpty(caseId) || numGames < 1))
            {

                MobileTribunal.GetInstance().caseLoader.loadNewCase(caseId, numGames, new AsyncCallback(CaseLoadedCallback));
            }
            else
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("An error occurred while trying to load a case.");
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                });
                return;
            }
        }
开发者ID:Cole119,项目名称:MobileTribunal,代码行数:45,代码来源:LoadingPage.xaml.cs

示例8: BackgroundWorkerDoWork

 private void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
 {
     var url = string.Format("http://www.youtube.com/watch?v={0}", e.Argument);
     _errorMessage = string.Empty;
     var request = (HttpWebRequest)WebRequest.Create(url);
     var response = (HttpWebResponse)request.GetResponse();
     var responseStream = response.GetResponseStream();
     if (responseStream == null)
     {
         _errorMessage = "Error while reading response from YouTube.";
         return;
     }
     var source = new StreamReader(responseStream, Encoding.UTF8).ReadToEnd();
     
     var found = source.IndexOf("x-flv");
     while (!source.Substring(found, 4).Equals("http"))
         found--;
     source = source.Remove(0, found);
     source = HttpUtility.UrlDecode(source);
     source = HttpUtility.UrlDecode(source); //Twice
     _errorMessage = source.Substring(0,source.IndexOf("&quality"));
 }
开发者ID:fbmly007,项目名称:3dsexplorer,代码行数:22,代码来源:YouTube.cs

示例9: RaygunRequestMessage

        public RaygunRequestMessage(HttpContext context)
        {
            HostName = context.Request.Url.Host;
              Url = context.Request.Url.AbsolutePath;
              HttpMethod = context.Request.RequestType;
              IPAddress = context.Request.UserHostAddress;
              Data = ToDictionary(context.Request.ServerVariables);
              QueryString = ToDictionary(context.Request.QueryString);
              Headers = ToDictionary(context.Request.Headers);
              Form = new NameValueCollection();

              foreach (string s in context.Request.Form)
              {
            if (String.IsNullOrEmpty(s)) continue;

            string name = s;
            string value = context.Request.Form[s];

            if (s.Length > 256)
            {
              name = s.Substring(0, 256);
            }

            if (value.Length > 256)
            {
              value = value.Substring(0, 256);
            }

            Form.Add(name, value);
              }

              try
              {
            var contentType = context.Request.Headers["Content-Type"];
            if (contentType != "text/html" && contentType != "application/x-www-form-urlencoded" && context.Request.RequestType != "GET")
            {
              int length = 4096;
              string temp = new StreamReader(context.Request.InputStream).ReadToEnd();
              if (length > temp.Length)
              {
            length = temp.Length;
              }

              RawData = temp.Substring(0, length);
            }
              }
              catch (HttpException)
              {
              }
        }
开发者ID:nicwise,项目名称:raygun4net,代码行数:50,代码来源:RaygunRequestMessage.cs

示例10: GetKeyFromRemoteServer

 public static int GetKeyFromRemoteServer(string regURL)
 {
     string s = new StreamReader(WebRequest.Create(regURL).GetResponse().GetResponseStream(), true).ReadToEnd().ToLower();
     int index = s.IndexOf("answer:");
     if (index != -1)
     {
         s = s.Substring(index + 7, 1);
         int result = 0;
         if (int.TryParse(s, out result))
         {
             return result;
         }
     }
     return -1;
 }
开发者ID:tmsdy,项目名称:RegRainbowEcommerce,代码行数:15,代码来源:Util.cs

示例11: Parse

        /// <summary>
        /// Processes the standard output and populates the relevant test result data of the referenced collection
        /// </summary>
        /// <param name="collection">test result collection where the leak information data will be inserted at</param>
        public override void Parse(TestResultCollection collection)
        {
            // NOTE Disposing is handled by parent class
            string strConsoleOutput = new StreamReader(this.InputStream).ReadToEnd();

            //the below regex is intended to only to "detect" if any memory leaks are present. Note that any console output printed by the test generally appears before the memory leaks dump.
            Regex regexObj = new Regex(@"Detected\smemory\sleaks!\nDumping objects\s->\n(.*)Object dump complete.", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline);
            Match outputMatch = regexObj.Match(strConsoleOutput);

            //leak has been detected
            if (outputMatch.Success)
            {
                RegisterMemoryLeak(outputMatch.Groups[1].Value, collection);
            }

            // Extract non-memory leak output
            string output = strConsoleOutput.Substring(0, ((outputMatch.Success) ? outputMatch.Index : strConsoleOutput.Length));
            RegisterMessages(output, collection);
        }
开发者ID:Flamefire,项目名称:vs-boost-unit-test-adapter,代码行数:23,代码来源:BoostConsoleOutputBase.cs

示例12: DebugConsoleOnReceivedTests

        public async Task DebugConsoleOnReceivedTests(bool connect)
        {
            // Setup
            var env = new Mock<IEnvironment>();
            var tracer = new Mock<ITracer>();
            var settings = new Mock<IDeploymentSettingsManager>();
            var process = new Mock<IProcess>();
            var connectionId = Guid.NewGuid().ToString();
            var data = Guid.NewGuid().ToString();
            var mem = new MemoryStream();

            using (var controller = new PersistentCommandTest(env.Object, settings.Object, tracer.Object, process.Object))
            {
                // Setup
                process.SetupGet(p => p.StandardInput)
                       .Returns(new StreamWriter(mem));

                // Test
                if (connect)
                {
                    await controller.Connect(Mock.Of<IRequest>(), connectionId);
                }

                await controller.Receive(Mock.Of<IRequest>(), connectionId, data);

                // Assert
                Assert.Equal(1, PersistentCommandTest.ProcessCount);

                if (connect)
                {
                    Assert.True(mem.Position > 0, "must write data");

                    mem.Position = 0;
                    var result = new StreamReader(mem).ReadToEnd();
                    Assert.True(result.EndsWith("\r\n"));
                    Assert.Equal(data, result.Substring(0, result.Length - 2));
                }
                else
                {
                    Assert.True(mem.Position == 0, "must skip data");
                }
            }
        }
开发者ID:40a,项目名称:kudu,代码行数:43,代码来源:DebugConsoleFacts.cs

示例13: RaygunRequestMessage

    public RaygunRequestMessage(HttpRequest request, RaygunRequestMessageOptions options)
    {
      options = options ?? new RaygunRequestMessageOptions();

      HostName = request.Url.Host;
      Url = request.Url.AbsolutePath;
      HttpMethod = request.RequestType;
      IPAddress = GetIpAddress(request);
      
      QueryString = ToDictionary(request.QueryString, null);

      Headers = ToDictionary(request.Headers, options.IsHeaderIgnored);
      Headers.Remove("Cookie");

      Form = ToDictionary(request.Form, options.IsFormFieldIgnored, true);
      Cookies = GetCookies(request.Cookies, options.IsCookieIgnored);

      // Remove ignored and duplicated variables
      Data = ToDictionary(request.ServerVariables, options.IsServerVariableIgnored);
      Data.Remove("ALL_HTTP");
      Data.Remove("HTTP_COOKIE");
      Data.Remove("ALL_RAW");

      try
      {
        var contentType = request.Headers["Content-Type"];
        if (contentType != "text/html" && contentType != "application/x-www-form-urlencoded" && request.RequestType != "GET")
        {
          int length = 4096;
          request.InputStream.Seek(0, SeekOrigin.Begin);
          string temp = new StreamReader(request.InputStream).ReadToEnd();
          if (length > temp.Length)
          {
            length = temp.Length;
          }

          RawData = temp.Substring(0, length);
        }
      }
      catch (HttpException)
      {
      }
    }
开发者ID:ArturDorochowicz,项目名称:raygun4net,代码行数:43,代码来源:RaygunRequestMessage.cs

示例14: MetaTag

        public void MetaTag()
        {

            var encoder = Encoding.GetEncoding("windows-1255");

            var html = htmlStart + htmlStartMeta + htmlStart3 +hebrewChar + htmlEnd;
            var htmlNoRecode = htmlStart + htmlStart3 + hebrewChar + htmlEnd;


            // create a windows-1255 encoded stream
            
            var dom = CQ.Create(GetMemoryStream(htmlNoRecode, encoder));

            // grab the character from CsQuery's output, and ensure that this all worked out.
            
            var csqueryHebrewChar = dom["#test"].Text();

            // Test directly from the stream

            string htmlHebrew = new StreamReader(GetMemoryStream(htmlNoRecode,encoder),encoder).ReadToEnd();

            var sourceHebrewChar = htmlHebrew.Substring(htmlHebrew.IndexOf("test>") + 5, 1);

            // CsQuery should fail to parse it

            Assert.AreNotEqual(sourceHebrewChar, csqueryHebrewChar);


            // the actual character from codepage 1255
            Assert.AreEqual("₪", sourceHebrewChar);

            // Now try it same as the original test - but with the meta tag identifying character set.

            var htmlWindows1255 = GetMemoryStream(html, encoder);

            // Now run again with the charset meta tag, but no encoding specified.
            dom = CQ.Create(htmlWindows1255);

            csqueryHebrewChar = dom["#test"].Text();

            Assert.AreEqual(sourceHebrewChar,csqueryHebrewChar);
        }
开发者ID:emrahoner,项目名称:CsQuery,代码行数:42,代码来源:CharacterSetEncoding.cs

示例15: Execute

        public void Execute(IJobExecutionContext context)
        {
            try
            {
                var urls = context.Get("urls").ToString().Split(',');

                urls.ToList().ForEach(url =>
                {
                    var request = (HttpWebRequest)WebRequest.Create(url);
                    var s = new Stopwatch();
                    s.Start();
                    using (var response = (HttpWebResponse)request.GetResponse())
                    using (var stream = response.GetResponseStream())
                    {
                        string ret = string.Empty;
                        if (stream != null)
                        {
                            string readToEnd = new StreamReader(stream).ReadToEnd();
                            ret = string.Format("{0}...", readToEnd.Substring(0, 500));
                        }
                        s.Stop();

                        Publish(new PingerModel()
                        {
                            Time = DateTime.Now,
                            Url = url,
                            response = ret,
                            Status = response.StatusCode.ToString(),
                            StatusDescription = response.StatusDescription,
                            Duration = s.Elapsed,
                            ContentLength = response.ContentLength,
                            ContentType = response.ContentType
                        });
                    }
                });
            }
            catch (Exception ex)
            {
                throw new JobExecutionException(ex);
            }
        }
开发者ID:thatandyrose,项目名称:appharbor-workers,代码行数:41,代码来源:Pinger.cs


注:本文中的System.IO.StreamReader.Substring方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。