Search code examples
c#.nettext-parsing

Parse a specific string from a converted bytes string


I have URL file which is being returned in bytes, I am reading these bytes using stream reader to get the data in the file. Converted .URL data as below.

[DEFAULT]
BASEURL=http://someUrl.com/employee-view/index.aspx?id=123
[InternetShortcut]
URL=http://someUrl.com/employee-view/index.aspx?id=123\0

I want to parse just the base URL string -- http://someUrl.com/employee-view/index.aspx?id=123

I am able to extract the baseUrl string using the following code. But I am looking for a better way.

  using (var reader = new StreamReader(new MemoryStream(docStream.DocumentBytes)))
   {
       string f = reader.ReadToEnd();

       if (!string.IsNullOrWhiteSpace(f))
       {
          string[] arr = f.Split('=');
          StringBuilder url = new StringBuilder(arr[1]);
          var a = arr[2].Split('[')[0];
          url.Append(SR.Common.Equals).Append(a);

          string finalUrl = url.ToString();

      } 
   }

All I need is the base URL string -- http://someUrl.com/employee-view/index.aspx?id=123


Solution

  • Well, If you mean a smaller code

    Using Linq:

    finalUrl = f.Replace("\0","").Replace("\r","")
        .Split('\n')
        .FirstOrDefault(x=>x.StartsWith("URL"))
        .Split(new[] {'='},2)[1];
    

    Using Regex:

    finalUrl = Regex.Match(f,@"(?<=URL\=).+").Value;