How to check if two files are the same .NET C#? - c#

How can I check if the contents of a file and some words that were inputted are the same? I want to make some sort of activation system, where it will check if the contents are the same as the input.
Here's what I want to do:
using System.Collections.Generic;
using System;
using System.IO;
namespace Example {
public class Example() {
string input = Console.ReadLine();
if (input == File(#"/prodkey.txt") {
//code
}
}
}

You can use File.ReadAllText(filePath) to get the contents of a text file, and then compare them using the == operator, or the string.Equals method (which provides for case-insensitive comparison):
string input = Console.ReadLine();
string fileContent = File.ReadAllText(#"/prodkey.txt");
if (input == fileContent)
{
}
// Or, for case-insensitive comparison:
if (input.Equals(fileContent, StringComparison.OrdinalIgnoreCase))
{
}

Related

Regex for string without spacial characters or spaces [duplicate]

How do I check a string to make sure it contains numbers, letters, or space only?
In C# this is simple:
private bool HasSpecialChars(string yourString)
{
return yourString.Any(ch => ! char.IsLetterOrDigit(ch));
}
The easiest way it to use a regular expression:
Regular Expression for alphanumeric and underscores
Using regular expressions in .net:
http://www.regular-expressions.info/dotnet.html
MSDN Regular Expression
Regex.IsMatch
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
if(regexItem.IsMatch(YOUR_STRING)){..}
string s = #"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c)
|| Char.IsWhiteSpace(c)).ToArray());
if (s != withoutSpecial)
{
Console.WriteLine("String contains special chars");
}
Try this way.
public static bool hasSpecialChar(string input)
{
string specialChar = #"\|!#$%&/()=?»«#£§€{}.-;'<>_,";
foreach (var item in specialChar)
{
if (input.Contains(item)) return true;
}
return false;
}
String test_string = "tesintg#$234524##";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
// Good-to-go
}
An example can be found here: http://ideone.com/B1HxA
If the list of acceptable characters is pretty small, you can use a regular expression like this:
Regex.IsMatch(items, "[a-z0-9 ]+", RegexOptions.IgnoreCase);
The regular expression used here looks for any character from a-z and 0-9 including a space (what's inside the square brackets []), that there is one or more of these characters (the + sign--you can use a * for 0 or more). The final option tells the regex parser to ignore case.
This will fail on anything that is not a letter, number, or space. To add more characters to the blessed list, add it inside the square brackets.
Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:
[a-zA-Z0-9 ]
You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:
using System;
using System.Linq;
namespace CheckStringContent
{
class Program
{
static void Main(string[] args)
{
//Get a password to check
Console.WriteLine("Please input a Password: ");
string userPassword = Console.ReadLine();
//Check the string
bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));
//Write results to console
Console.WriteLine($"Symbols are present: {symbolCheck}");
}
}
}
This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.
A great way using C# and Linq here:
public static bool HasSpecialCharacter(this string s)
{
foreach (var c in s)
{
if(!char.IsLetterOrDigit(c))
{
return true;
}
}
return false;
}
And access it like this:
myString.HasSpecialCharacter();
private bool isMatch(string strValue,string specialChars)
{
return specialChars.Where(x => strValue.Contains(x)).Any();
}
Create a method and call it hasSpecialChar with one parameter
and use foreach to check every single character in the textbox, add as many characters as you want in the array, in my case i just used ) and ( to prevent sql injection .
public void hasSpecialChar(string input)
{
char[] specialChar = {'(',')'};
foreach (char item in specialChar)
{
if (input.Contains(item)) MessageBox.Show("it contains");
}
}
in your button click evenement or you click btn double time like that :
private void button1_Click(object sender, EventArgs e)
{
hasSpecialChar(textbox1.Text);
}
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
Add the [https://www.nuget.org/packages/Extensions.cs][1] package to your project.
Add "using Extensions;" to the top of your code.
"smith23#".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
Every other check in the rest of the code is simply MyString.IsAlphaNumeric().
Based on #prmph's answer, it can be even more simplified (omitting the variable, using overload resolution):
yourString.Any(char.IsLetterOrDigit);
No special characters or empty string except hyphen
^[a-zA-Z0-9-]+$

C# Ask user another input

I am creating a soundDex application and I need to ask the user for a second name after they have inputted the first one. I also want "error no input" if the user does not input a second name. How would I do this within my soundDex?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoundDexFinal
{
class Program
{
static void Main(string[] args)
{
string input = null;
bool good = false;
Console.WriteLine("SoundDex is a phonetic algorithm which allows a user to encode words which sound the same into digits."
+ "The program allows the user essentially to enter two names and get an encoded value.");
while (!good) // while the boolean is true
{
Console.WriteLine("Please enter a name -> "); // asks user for an input
input = Console.ReadLine();
// Make sure the user entered something
good = !string.IsNullOrEmpty(input); // if user enters a string which is null or empty
if (!good) // if boolean is true
Console.WriteLine("Error! No input."); // displays an error to the user
}
soundex soundex = new soundex(); // sets new instance variable and assigns from the method
Console.WriteLine(soundex.GetSoundex(input)); // gets the method prior to whatever the user enters
Console.ReadLine(); // reads the users input
}
class soundex
{
public string GetSoundex(string value)
{
value = value.ToUpper(); // capitalises the string
StringBuilder soundex = new StringBuilder(); // Stringbuilder holds the soundex code or digits
foreach (char ch in value) // gets the individual chars via a foreach which loops through the chars
{
if (char.IsLetter(ch))
AddChar(soundex, ch); // When a letter is found this will then add a char
} // soundex in (parameter) is for adding the soundex code or digits
return soundex.ToString(); //return the value which is then converted into a .String()
}
private void AddChar(StringBuilder soundex, char character) //encodes letter as soundex char and this then gets appended to the code
{
string code = GetSoundexValue(character);
if (soundex.Length == 0 || code != soundex[soundex.Length - 1].ToString())
soundex.Append(code);
}
private string GetSoundexValue(char ch)
{
string chString = ch.ToString();
if ("BFPV".Contains(chString)) // converts this string into a value returned as '1'
return "1";
else if ("CGJKQSXZ".Contains(chString)) // converts this string into a value returned as '2'
return "2";
else if ("DT".Contains(chString)) // converts this string into a value returned as '3'
return "3";
else if ("L".Contains(chString)) // converts this string into a value returned as '4'
return "4";
else if ("MN".Contains(chString)) // converts this string into a value returned as '5'
return "5";
else if ("R".Contains(chString)) // converts this string into a value returned as '6'
return "6";
else
return ""; // if it can't do any of these conversions then return nothing
}
}
}
}
I admit, I am not entirely clear on what part precisely you're having trouble with. But the specific goal is stated clearly enough, and you've provided a sufficient code example, so…
The basic problem is "how do I require the user to input the same kind of data more than once?" The basic answer is the same as for any programming problem that involves having to repeat an action: generalize that action into a subroutine (i.e. "method" in C# parlance) that will perform that action, and call the subroutine every time you need to perform the action.
For example:
class Program
{
static void Main(string[] args)
{
string input1, input2;
Console.WriteLine("SoundDex is a phonetic algorithm which allows a user to encode words which sound the same into digits."
+ "The program allows the user essentially to enter two names and get an encoded value.");
input1 = GetValidInput("Please enter a name -> ");
input2 = GetValidInput("Please enter a second name -> ");
soundex soundex = new soundex(); // sets new instance variable and assigns from the method
Console.WriteLine(soundex.GetSoundex(input1)); // gets the method prior to whatever the user enters
// do whatever you want with input2 as well
Console.ReadLine(); // reads the users input
}
static string GetValidInput(string prompt)
{
while (true)
{
string input;
Console.WriteLine(prompt); // asks user for an input
input = Console.ReadLine();
// Make sure the user entered something
if (!string.IsNullOrEmpty(input))
{
return input;
}
Console.WriteLine("Error! No input."); // displays an error to the user
}
}
}

C# Splitting another string

I am wanting to split the next string which is "L" but it is not working for some reason. I have managed to make this work for my first substring and it seems to be working but this is not working for my second substring which should return "L" within the console in a new line or the 20th character. Any ideas?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace employeefinal
{
class Program
{
static void Main(string[] args)
{
employee i = new employee();
Console.WriteLine(i.getName());
Console.ReadLine();
Console.WriteLine(i.getCity());
Console.ReadLine();
}
public class employee
{
string employeename = "Name:John How Smith L, U, 012, 2, 7, 2, 4";
public employee()
{
}
public string getName()
{
return employeename.Substring(0, 19).Trim();
}
public string getCity()
{
return employeename.Substring(19, 20).Trim();
}
}
}
}
With Substring the second parameter is the length of the substring. If you just want getCity to return 'L' you could change it to:
return employeename.Substring(20,1).Trim();
Substring() method accepts two things one is character position and length from that position. In your code GetName() returns starting from zero position to 19th position and in 2nd method ie GetCity() returns from 19th position to rest of character in that string. So substring(19,2) will work I guess.

Converting string to double in C#

I have a long string with double-type values separated by # -value1#value2#value3# etc
I splitted it to string table. Then, I want to convert every single element from this table to double type and I get an error. What is wrong with type-conversion here?
string a = "52.8725945#18.69872650000002#50.9028073#14.971600200000012#51.260062#15.5859949000000662452.23862099999999#19.372202799999250800000045#51.7808372#19.474096499999973#";
string[] someArray = a.Split(new char[] { '#' });
for (int i = 0; i < someArray.Length; i++)
{
Console.WriteLine(someArray[i]); // correct value
Convert.ToDouble(someArray[i]); // error
}
There are 3 problems.
1) Incorrect decimal separator
Different cultures use different decimal separators (namely , and .).
If you replace . with , it should work as expected:
Console.WriteLine(Convert.ToDouble("52,8725945"));
You can parse your doubles using overloaded method which takes culture as a second parameter. In this case you can use InvariantCulture (What is the invariant culture) e.g. using double.Parse:
double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);
You should also take a look at double.TryParse, you can use it with many options and it is especially useful to check wheter or not your string is a valid double.
2) You have an incorrect double
One of your values is incorrect, because it contains two dots:
15.5859949000000662452.23862099999999
3) Your array has an empty value at the end, which is an incorrect double
You can use overloaded Split which removes empty values:
string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
Add a class as Public and use it very easily like convertToInt32()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for Common
/// </summary>
public static class Common
{
public static double ConvertToDouble(string Value) {
if (Value == null) {
return 0;
}
else {
double OutVal;
double.TryParse(Value, out OutVal);
if (double.IsNaN(OutVal) || double.IsInfinity(OutVal)) {
return 0;
}
return OutVal;
}
}
}
Then Call The Function
double DirectExpense = Common.ConvertToDouble(dr["DrAmount"].ToString());
Most people already tried to answer your questions.
If you are still debugging, have you thought about using:
Double.TryParse(String, Double);
This will help you in determining what is wrong in each of the string first before you do the actual parsing.
If you have a culture-related problem, you might consider using:
Double.TryParse(String, NumberStyles, IFormatProvider, Double);
This http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx has a really good example on how to use them.
If you need a long, Int64.TryParse is also available: http://msdn.microsoft.com/en-us/library/system.int64.tryparse.aspx
Hope that helps.
private double ConvertToDouble(string s)
{
char systemSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator[0];
double result = 0;
try
{
if (s != null)
if (!s.Contains(","))
result = double.Parse(s, CultureInfo.InvariantCulture);
else
result = Convert.ToDouble(s.Replace(".", systemSeparator.ToString()).Replace(",", systemSeparator.ToString()));
}
catch (Exception e)
{
try
{
result = Convert.ToDouble(s);
}
catch
{
try
{
result = Convert.ToDouble(s.Replace(",", ";").Replace(".", ",").Replace(";", "."));
}
catch {
throw new Exception("Wrong string-to-double format");
}
}
}
return result;
}
and successfully passed tests are:
Debug.Assert(ConvertToDouble("1.000.007") == 1000007.00);
Debug.Assert(ConvertToDouble("1.000.007,00") == 1000007.00);
Debug.Assert(ConvertToDouble("1.000,07") == 1000.07);
Debug.Assert(ConvertToDouble("1,000,007") == 1000007.00);
Debug.Assert(ConvertToDouble("1,000,000.07") == 1000000.07);
Debug.Assert(ConvertToDouble("1,007") == 1.007);
Debug.Assert(ConvertToDouble("1.07") == 1.07);
Debug.Assert(ConvertToDouble("1.007") == 1007.00);
Debug.Assert(ConvertToDouble("1.000.007E-08") == 0.07);
Debug.Assert(ConvertToDouble("1,000,007E-08") == 0.07);
In your string I see: 15.5859949000000662452.23862099999999 which is not a double (it has two decimal points). Perhaps it's just a legitimate input error?
You may also want to figure out if your last String will be empty, and account for that situation.

Which method to use to remove string characters in stringBuilder class

I would to know, Is there any method in StringBuilder class in C#, which can remove string characters without changing other character of same value within different index?
Like for a string like "5002", what if want to remove character in first index to "3"?
I'm using StringBuilder's remove method for the specified string and it's returning me an output as "5332" instead of "5302"?
The code which I'm using to accomplish my requirement is:
StringBuilder j = new StringBuilder("5002");
Console.WriteLine(j.Replace(j.ToString(1, 1),"3");
Well, you can use the indexer:
builder[1] = '3';
Is that what you're after?
For example:
using System;
using System.Text;
class Test
{
static void Main()
{
StringBuilder builder = new StringBuilder("5002");
builder[1] = '3';
Console.WriteLine(builder); // Prints 5302
}
}

Categories