var temp = toCheck.GetData(DataFormats.FileDrop);
I have the code above in my program. toCheck is an IDataObjecct containing a file(image to be specific) path.
When I debug, I see the value stored under as such:
temp -> {string[1]}
[0] -> "C:\....rest of path"
Everything is correct but when I try to access the string inside, I cannot. If I use the toString() method it returns System.String[] but not the filepath.
Any suggestions on how I can retrieve the filepath inside of the variable?
temp -> {string[1]} Means that temp is an array of type string with one element.
[0] -> "C:\....rest of path" Means that the element at index 0 is equal to the path.
Since GetData returns the string array boxed as an object, you'll also have to unbox it first. Then you can simply access that element like this:
string[] strArr = temp as string[];
string s = temp[0];
temp is an array of strings, that is why you are getting that. If you want to get the first string of the array then:
var mystring = temp[0];
That should do
Also you can check if the string[] has any string with:
if(temp.Length > 0) myString = temp[0];
where myString is a variable of type string
I found the answer!
string[] arr = ((IEnumerable)temp).Cast<object>().Select(x => x.ToString()).ToArray();
Using the above statement you can go from type object to an array of string.
You need to have included using.System.Linq for it to work.
var temp = toCheck.GetData(DataFormats.FileDrop);
string[] arr = ((IEnumerable)temp).Cast<object>().Select(x => x.ToString()).ToArray();
string path = "";
foreach(string a in arr)
path = a;
This ended up being all the code if anybody is curious. I iterate over the array because otherwise it would skip the rest of the function when I debugged. Not sure what was causing this but this works. Thank you all for your help!
Related
Hi I am new to programming. I would like to read a text file and take the values ( strings ) and store each character of the string in an array individually. I have used a list to take in the vales from the text file. I am finding it difficult to move them into an array and then use those values in my program. Please find me a solution if possible. Thanking you in advance.
public class file_IO
{
string[] letters = new string[] //I would like to store it in this variable
public void File_Reader()
{
string filepath = #"env.txt"; //Variable to hold string
List<string> file_lines = File.ReadAllLines(filepath).ToList();//returns array of strings into List
foreach (string line in file_lines)
{
}
}
}
Hope this will work for you!.
public char[] File_Reader()
{
string filepath = #"env.txt"; //Variable to hold string
StreamReader sr = new StreamReader(filepath);
string fileContentInString = sr.ReadToEnd();
sr.Close();
return fileContentInString.ToCharArray();
}
List<List<char>> linesAsChars = File.ReadAllLines(filepath)
.Select(l => l.ToList())
.ToList();
This will get a List of List of chars.
string implements IEnumerable<char>, so with ToList each line in the file is translated to List<char>.
Solution to "store each character of the string in an array individually" is fairly easy because string is in fact an array of char. You can do this using something like this :
char[] letters;
public void File_Reader()
{
string filepath = #"env.txt";
letters = File.ReadAllText(filePath).ToArray();
}
I'm not really sure if I have understood your question properly, but from what I have read, I will assume that you want an array of lines (which are strings).
In this case, you don't need to do much as the File.ReadAllLines() method naturally outputs an array of string variables.
Remove the for loop and replace
List<string> file_lines = File.ReadAllLines(filepath).ToList();//returns array of strings into List
with:
letters = File.ReadAllLines(filepath)
In case what you want is actually an array of every char value in your file, I would refer to #m.rogalski's answer and declare an array of char[], for example, declare:
char[] fileChars;
and then replace the line I mentioned earlier with:
fileChars = readAllText(filePath).toCharArray()
You will notice that you do not need a loop in either of the above situations. Hope I helped.
It keeps giving me an error message here and I don't understand why.
int[] user31 = new int[53];
user31 = System.IO.File.ReadLines("ratings.txt").Skip(1675).Take(53).ToArray();
Because ReadLines returns strings, you know. It is right there in the documentation:
http://msdn.microsoft.com/en-us/library/dd383503(v=vs.110).aspx
and you just do "TOArray".
If you would parse the rows before doing ToArray....
Skip(1675).Take53.Select (x=> Int.Parse(x)).ToArray()
(or along this line)
You would get an array of ints, but calling ToArray on an enum of string returns an array of strings.
Just look at the return type of System.IO.File.ReadLines methods. It is String[].
You call Skip and Take as a result you will have an IEnumerable<String> calling ToArray again will give you a String[] not int[].
Because each line of a text file is just that, text. If you can guarantee that each line is actually an integer, you can do something like this:
int[] user31 = new int[53];
string[] lines = System.IO.File.ReadLines("ratings.txt").Skip(1675).Take(53).ToArray();
int i = 0;
foreach (var line in lines)
{
user31[i++] = Convert.ToInt32(lines[i]);
}
ReadLines returns strings with an array
I assume that your ratings.txt file contain int values in each line
you need to convert string array to int array ..
int[] user31 = new int[53];
user31= System.IO.File.ReadLines("ratings.txt").Skip(1675).Take(53).ToArray().Select(n => Convert.ToInt32(n)).ToArray();
This is because the user31 is an integer array but ReadLine returns string[].
Try like this:
List<string> str =new List<string>(new string[] {"123", "234","345","456","678","678","890"});
List<int> a = str.Skip(1675).Take(53).ConvertAll(new Converter<string, int>(int.Parse));
No need to explicitly parse it yourself and return an array. ConvertAllwill do the job to return an array.
EDIT:
Included a running test case using ConvertAll function.
I have string file with content like this
string a = "12,1,______,_,__;1,23,122;"
I want to grab only this integer value 23. Problem is that this conntent is dynamic and I it's lenght can be changed, so this string a can easily be in the next iteration like
string a = "12,1,______,_,__;11,2,1;"
In this case I would grab integer 2.
If the structure is always the same, then:
Split the string, and grab the element before last.
var array1 = a.Split(';');
// check the array length if it's needed to avoid
// IndexOutOfRangeException exception
var array2 = array1[1].Split(',');
var yourNumber = array2[array2.Length - 2]
String.Split
Ignoring error checking for a minute, this would work:
string a = "12,1,______,_,__;11,2,1;"
int i = Int32.Parse(String.Split(',')[5])
If this is the route you will go, you should take extra care to verify your input. Check the length of the array reutrned from Split, and verify that the 5th value can indeed be parsed to an int.
Try this regex:
(?<=;\d*,)\d*(?=,\d*;)
Sample usage:
class Program
{
static void Main(string[] args)
{
string a = "12,1,______,_,__;1,23,122;";
var regex = new Regex(#"(?<=;\d*,)\d*(?=,\d*;)");
Console.WriteLine(regex.Match(a).Value);
a = "12,1,______,_,__;11,2,1;";
Console.WriteLine(regex.Match(a).Value);
}
}
Try this:
var number = a.split(",")[5];
another option is to split the text into array (if they have same pattern):
var output = a.Split(",;".ToCharArray());
var value = output[theIndex]; // get the index you want
I have a method that takes an ArrayList object as a parameter.
I then try to convert this arrayList into a string array but get an InvalidCastException.
The ArrayList contains a seven random numbers. As they are of the type object I am assuming it shouldnt be a problem casting it into a string.
This is the method that I have called
p.matches(winningNumber);
public void matches(ArrayList al)
{
try
{
string nameFile;
string[] winningNumber = (string[])al.ToArray(typeof(string));
Console.WriteLine("Please enter the name of the file you want to Read from");
nameFile = Console.ReadLine();
it is with the attemt at casting that I get an exception.
You are getting this exception because in order to convert to array of strings, the elements themselves must be strings as well. You can do it with LINQ, though:
string[] winningNumber = al.Cast<object>().Select(o => o.ToString()).ToArray();
To deal with nulls, replace o.ToString() with ""+o or a conditional that checks for nulls.
You just need to use Enumerable.Cast before you call ToArray
string[] winningNumber = al.Cast<string>().ToArray();
Change
string[] winningNumber = (string[])al.ToArray(typeof(string));
To
string[] winningNumber = al.Cast<object>.Select(x=> x==null ? string.Empty : x.ToString()).ToArray();
If you have some items that are not string, you can use Enumerable.OfType. It will ignore non string types.
string[] winningNumber = al.OfType<string>().ToArray();
string[] winningNumber = al.Cast<object>.Select(x=>Convert.ToString(x)).ToArray();
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C# Textbox string separation
I want to pass the string value ie (red,blue,black) to a string array. I used the following code
string[] splitString = myString;
I am getting this error
Error 137 Argument '1': cannot convert from 'string' to 'char[]'
regards,
string[] splitString = myString.Split(",");
Try Split method of String class:
myString.Split(',');
To have a complete grip over various scenerios, you can visit .Net Perls
You should have a look at the String.Split method
string myString = "red,blue,black";
string[] splitString = myString.Split(',');
You are trying to assign a string directly to a string[] - this can't work. You need to do something with the string first - the String.Split method looks like a good fit:
string[] splitString = "red,blue,black".Split(',');
string myString = "red,blue,black";
string[] splitString = myString.Split(',');
foreach(string s in splitString)
Console.WriteLine(s);
Try it like below,
string myString = "red,blue,green";
string[] splitString = new string[1];
splitString[0] = myString;
or
string[] splitString = myString.Split(',');
string.Split()
Or just for an alternative:
string myString = "red,blue,black";
var strArr = Regex.Split(myString, ",");
If I read your question correctly you're not trying to split the string, you just need an array with one or more strings, right? In that case you'd do something like this:
string[] splitString = new string[]{ "red", "blue", "black" };
Your problem is that, you try to assign a type to array of type.
If you declare an array, then you need to initialize it with operator new.
String[] arrayOfString = new String[3];
In above piece of code you declare a variable arrayOfString that is an array of String object. This mean that in arrayOfString you can expect String.
After that you assign to it new array instance for three String objctes (new String[3]), in this step you only reserve memory for three elements.
After this you are able to store any String object in arrayOfString.
To store a object in array you just have to use the variable name and indexer.
arrayOfString[0] = "StackOverflow";
In this example we assign, an String into arryOfString under index 0.
In C# array are indexed from 0 to declared size - 1, that in this case is 2.