How to check if a string contains invalid filename characters in c#? - c#

I have a string and I want to check if it contains any invalid filename characters. I know I could use
Path.GetInvalidFileNameChars
to get a array of invalid filename characters and loop through to see if the string contains any invalid char. But is there a easier and shorter expression? It is c#. So can anyone help?

bool containsInValidFilenameCharacters(string str) {
return str.Any(Path.GetInvalidFileNameChars().Contains)
}
Note that this is the same as doing
var invalidChars = Path.GetInvalidFileNameChars();
return str.Any(c => invalidChars.Contains(c));
But since the type signature of Contains matches up exactly with the parameter delegate type of Any we can just pass it directly and it will do an implicit conversion.

Related

Convert byte array to string has special characters C#

I am going to convert byte array into string using below method.
string data = Encoding.Default.GetString(e.Data);
But this string has the following special characters which I needed to avoid from the string itself.
As you can see in the data I am getting space before the '7h' and some '\rL' getting added after the text. I used trim() function. But it didn't work for the following case.
Please advice.
If you know exactly symbols you whant remove, just replace it:
var data = "⏩Some⏬String";
var clearedData = data.Replace("⏩", string.Empty).Replace("⏬", string.Empty);
result:
SomeString

Casting HexNumber as character to string

I need to process a numeral as a string.
My value is 0x28 and this is the ascii code for '('.
I need to assign this to a string.
The following lines do this.
char c = (char)0x28;
string s = c.ToString();
string s2 = ((char)0x28).ToString();
My usecase is a function that only accepts strings.
My call ends up looking cluttered:
someCall( ((char)0x28).ToString() );
Is there a way of simplifying this and make it more readable without writing '(' ?
The Hexnumber in the code is always paired with a Variable that contains that hex value in its name, so "translating" it would destroy that visible connection.
Edit:
A List of tuples is initialised with this where the first item has the character in its name and the second item results from a call with that character.
One of the answers below is exactly what i am looking for so i incorporated it here now.
{ existingStaticVar0x28, someCall("\u0028") }
The reader can now instinctively see the connection between item1 and item2 and is less likely to run into a trap when this gets refactored.
You can use Unicode character escape sequence in place of a hex to avoid casting:
string s2 = '\u28'.ToString();
or
someCall("\u28");
Well supposing that you have not a fixed input then you could write an extension method
namespace MyExtensions
{
public static class MyStringExtensions
{
public static string ConvertFromHex(this string hexData)
{
int c = Convert.ToInt32(hexCode, 16);
return new string(new char[] {(char)c});
}
}
}
Now you could call it in your code wjth
string hexNumber = "0x28"; // or whatever hexcode you need to convert
string result = hexNumber.ConvertFromHex();
A bit of error handling should be added to the above conversion.

Cannot implicitly convert type 'string' to 'char[]'

I have the following code but giving an error "Cannot implicitly convert type 'string' to 'char[]'"
char[] hTempFile = new char[300 + 1];
hTempFile ="";
A char[] is different to a string. If you intend to be an empty array, then:
hTempFile = new char[0];
or perhaps simply (if you add a few null-checks):
hTempFile = null;
There is also .ToCharArray() on a string, but that seems overkill here.
Frankly, for a file-name, it sounds like you should actually be using string here.
It looks like a C style string initialization, in C# it is best to avoid using char arrays for strings and use the string class instead.
string hTempFile = string.Empty;
What do you want to achieve? you have already defined hTempFile as type char[].
You cannot assign a string value to hTempFile .
You can use String.ToCharArray() to get array of char from string....If the string is empty like in your given example, the returned array is empty and has zero length....
hTempFile = "".ToCharArray();
It looks like you want to set hTempFile to an empty string -- or, more specifically, the C-string representation of an empty string. If that's the case, all you need to do is
hTempFile[0] = 0;
Since C-strings are null-terminated, placing a null byte in the first char of the array effectively empties the string.

Compare string with character in C#

suppose there is a string like this
string temp2 = "hello";
char[] m = { 'u','i','o' };
Boolean B = temp2.Compare(m);
I want to check if the string contains my array of character or not?
I am trying but it is not taking.On compiling the message
temp2.Compare(m) should be String type
is coming.
Means it follows string.compare(string);
I hope it is not the way there should be some way to do that.
edit//
I have Corrected the line String.Compare return the Boolean Value
If what you want to determine is whether the string contains any of the characters in your array, you can use the string.IndexOfAny function.
bool containsAny = temp2.IndexOfAny(m) >= 0;

string value validation in C#

There is two variable was assigned the value of "003" and "00 3". And it was convert to byte[] as below.
Before:
myStr1 = "003"; // valid, there is no blank inserted.
myStr2 = "00 3"; // invalid, there is one blank character or multi blanks character inserted.
After converted by convert(), if there are blank characters found, the source string will be convert to byte array.
myVal1 = "3"; // valid after convert
myVal2[0] = 0; // invalid, since the source myStr2 is invalid.
myVal2[1] = 1; // same as above.
And now I need determine the source string is valid or invalid based on the converted result. I dont' know how to say the result is an byte array. Could you please give me some advice. Thanks in advance.
input string type source value as SourVal
if (ResultVal is Byte Array) // how to translate the statement to C# code?
SourVal is Invalid;
else if (ResultVal is still String type) // how to translate the statement to C# code?
SourVal is valid;
ps: I failed to try the methods of typeof() and gettype() at my practice. I don't know how to use the methods. Or there is other better method for my validation.
maybe use:
if (ResultVal is byte[]) {
// SourVal is Invalid;
} else if ( ResultVal is String ) {
//SourVal is valid;
}
Try using IsWhiteSpace
//Check the String for Blank spaces if found then don't convert
if(!str.Contains(" "))
{
//use the convert method
}
else
{
//Write Message for an Invalid String
}

Categories

Resources