-1

I'm trying to compare strings and I'm using a WebClient to download one of them and when I compare them, it always returns that they aren't equal even though they are.

here's the code

using System;
using System.Net;

class MainClass {
  public static readonly string test = "e";
  public static readonly string e = "http://raw.githubusercontent.com/SeizureSaladd/test/main/ok.txt";
  public static void Main (string[] args) {
         

    if(MainClass.test == new WebClient().DownloadString(MainClass.e))
    {
      Console.WriteLine("yay it works lol");
    }
    else
    {
      Console.WriteLine("uh oh");
      Console.WriteLine(new WebClient().DownloadString(MainClass.e));
    }
  }
}

if I run this, it says uh oh then returns e even though they're exactly the same.

Does anyone know how to fix this?

SeizureSalad
  • 23
  • 1
  • 6
  • I'd start off by assigning the WebClient response to it's own variable so that you can use the debugger to inspect what value is being returned. var webResponse = new WebClient().DownloadString(MainClass.e); if (MainClass.test == webResponse) – Andy Stagg Jun 17 '21 at 20:13
  • I'd also suggest following the documentation here: https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.downloadstring?view=net-5.0 and assign the web client to it's own variable as well. – Andy Stagg Jun 17 '21 at 20:17

3 Answers3

1

http://raw.githubusercontent.com/SeizureSaladd/test/main/ok.txt returns: "e\n". You'll need to strip the trailing new-line character to get a valid comparison. So no, they aren't equal at all.

glenebob
  • 1,943
  • 11
  • 11
  • GitHub keeps adding the \n to the file which is annoying even if i delete the new line thanks for you help – SeizureSalad Jun 17 '21 at 20:39
  • It's not necessarily GitHub's fault: https://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline It comes down to more of a standards thing. – Andy Stagg Jun 17 '21 at 20:53
1

WebClient.Download string returns "e\n" - so "e" != "e\n".

You can simply resolve this with Trim method:

string downloadString = new WebClient().DownloadString(e);
if (test == downloadString.Trim())
Anton Komyshan
  • 1,377
  • 10
  • 21
0

Because the response you get back is not "e" but "e\n"; If you download the file, then you see a extra new line. That is why it is not equal. The console will print this as a new line instead of "\n".

Oscar Veldman
  • 301
  • 2
  • 7