I'm trying to get all files in a directory but I want them associated with numbers. Now, I have this:
string[] ficheiro = Directory.GetFiles(#"C:\Users\David\Documents\Jogos\Jogos de emuladores\Roms GB\", "*.gba");
{
Console.WriteLine ("F1" + " - " + Path.GetFileNameWithoutExtension (ficheiro[0]));
}
Console.ReadKey ();
When I reach 10 files I will have a shortcut to flip a page to get more files (10 per page). I will list all files by hand. Like this:
Console.WriteLine ("F2" + " - " + Path.GetFileNameWithoutExtension (ficheiro[1]));
Console.WriteLine ("F3" + " - " + Path.GetFileNameWithoutExtension (ficheiro[2]));
Is there a better way of doing it?
You need to use a loop. You cannot do all of them "by hand" because you do not necessarily know how many there are.
var files = Directory.GetFiles(#"C:\Your\Directory\Path", "*.gba");
var count = 0;
foreach (var file in files)
{
if (count % 10 == 0 && count != 0)
{
Console.ReadLine();
}
count++;
Console.WriteLine("F{0} - {1}", count, Path.GetFileNameWithoutExtension(file));
}
Console.ReadLine();
You can iterate through the array with a for-loop :
string[] ficheiros = Directory.GetFiles(#"C:\Users\David\Documents\Jogos\Jogos de emuladores\Roms GB\", "*.gba");
for (int i = 0; i < ficheiros.Length; i++)
{
Console.WriteLine("F{0} - {1}", i + 1, Path.GetFileNameWithoutExtension(ficheiros[i]));
}
Console.ReadKey();
The key is to identify the repeating part and extract a pattern from it :
//only these changed V V
Console.WriteLine ("F2" + " - " + Path.GetFileNameWithoutExtension (ficheiro[1]));
Console.WriteLine ("F3" + " - " + Path.GetFileNameWithoutExtension (ficheiro[2]));
// just replace them and put it inside an appropriate loop, in this case a for-loop
for(int i = 0; i < ficheiro.Length; i++)
Console.WriteLine ("F" + (i+1) + " - " + Path.GetFileNameWithoutExtension (ficheiro[i]));
int i = 0;
var ficheiro = from s in Directory.GetFiles(#"C:\temp\", "*.*")
select ("F"+ i++ + "-" + s);
Related
I want to read string variable that contains this:
==title1==
text1...
==title2==
text2...
.
.
.
etc
I want to retrieve title1, title2 and etc sub strings, then create separate files like this:
title1.txt contains text1
title2.txt contains text2
how can I do this?
string[] split = yourString.Split(new string[] { "==" }, StringSplitOptions.None);
That will give you an array with these entrys: title1, text1, title2, text2 etc.
Now when you iterate through the array you will have the title every second loop. So increment by 2 and you will have the title at i and the corresponding text at i+1.
for (int i = 0; i < split.Length; i+=2){
File.WriteAllText("yourPath/" + split[i] + ".txt", split[i+1]);
}
I solve it by change code to this:
_edit = edit.InnerText.Replace("\n", Environment.NewLine);
// _edit = edit.InnerText.Replace("<lt;ref&", "<ref>");
// _edit = edit.InnerText.Replace("</ref>", "</ref>");
string[] split = _edit.Split(new[] { "==" }, StringSplitOptions.None);
System.IO.Directory.CreateDirectory(path + title);
using (StreamWriter sw = new StreamWriter(path + title + "\\" + "مقدمه.txt"))
{
sw.WriteLine(split[0]);
}
for (int i = 1; i < split.Length; i += 2)
{
//split[i].Replace("=", " ");
//File.WriteAllText(path + split[i] + ".txt", split[i + 1]);
using (StreamWriter sw = new StreamWriter(path + title + "\\" + split[i] + ".txt"))
{
// Add some text to the file.
sw.WriteLine(split[i + 1]);
}
}
public string completeHour(string theTime)
{
string total="";
string[] timeArray = theTime.Split(new[] { ":" }, StringSplitOptions.None);
string h = timeArray[0];
string i = timeArray[1];
string j = timeArray[2];
MessageBox.Show(h + "+" + i + "+" + j);
if (h == " " || i == " " || j == " ")
{
if (h == " ")
{
h = "00";
total = (String.Concat("00",theTime)).Trim();
MessageBox.Show(total);
}
else if (i == " ")
{
i = "00";
total = timeArray[0] + i + timeArray[2];
//MessageBox.Show("m-=" + total);
}
//else if (j == "")
//{
// j = "00";
// theTime = timeArray[0] + timeArray[1] + j;
// MessageBox.Show("s-=" + theTime);
//}
}
return total;
}
Why total is 00 :52:04 (for instance) and not 00:52:04 that was supposed to be?
If you'd like to make sure there are no leading or trailing white characters, you could call
string h = timeArray[0].Trim();
And then instead of checking the value against " ", you could compare it to String.Empty or call h.IsNullOrEmpty().
However I'd strongly recommend you to use simpler approach, using a DateTime object.
DateTime timeObject;
DateTime.TryParse(theTime, out timeObject);
and then just work with Hour, Minute and Second properties. This way you get away from custom parsing and make your code more object-oriented, thus easier to read, instead of juggling multiple string objects.
Best way to avoid this is using Trim() when assigning value to total in following two lines:
total = (String.Concat("00",theTime.Trim())).Trim();
.
.
.
total = timeArray[0].trim() + i + timeArray[2].Trim();
Although I was using a MaskedTextBox I didn't define a custom mask so, anywhere (I think) the system assumed that 'theTime' was the type of DateTime.
So, the result of String.Concat("00",theTime) was '00 :32:99', for instance.
I´ve solved it by using the variables h, i and j instead of theTime.
Using a DateTime variable was not appropriated because I want to allow the user to insert NULL values for the hours or for the minutes.
I have 1000's of images and more than 100,000 lines of log files. I need to check if there exists an image that is associated with each unix time in log file. To do this, I first read thru all the images and stored time information in an array. Then I read thru all the lines of the log file, split each information (lat, long, time) and stored them in an array. Finally, I am taking one time element at a time and checking if it matches with image time array. If no match is found, I get the time from log, get lat and long from the same array and write it to a text file. But the overall process takes very long time. I am looking into efficiencies on how to make this process faster.
var fileList = Directory.GetFiles(imageLocation, "*.jpg");
//Array that will store all the time information obtained from image property
double[] imgTimeInfo = new double[fileList.Length];
int imgTimeCounter =0;
foreach (var fileName in fileList)
{
x++;
string fileNameShort = fileName.Substring(fileName.LastIndexOf('\\') + 1);
richTextBox1.AppendText("Getting time information from image " + x + " of " + fileList.Length + " : " + fileNameShort + Environment.NewLine);
richTextBox1.Refresh();
using (var fs = File.OpenRead(fileName))
{
//create an instance of a bitmap image
var image = new Bitmap(fs);
//get the date/time image property of the image
PropertyItem property = image.GetPropertyItem(36867);
System.Text.Encoding encoding = new System.Text.ASCIIEncoding();
string valueFrmProperty = encoding.GetString(property.Value);
//Format the value obtained to convert it into unix equivalent for comparison
string valueCorrected = valueFrmProperty.Split(' ')[0].Replace(":", "/") + " " + valueFrmProperty.Split(' ')[1];
var unixTime = ConvertToUnixTimeStamp(DateTime.Parse(valueCorrected));
imgTimeInfo[imgTimeCounter] = unixTime;
imgTimeCounter++;
//It is very important to dispose the image resource before trying to read the property of another image. image.dispose frees the resources or else we get
//outofmemoryexception.
image.Dispose();
}
}
MessageBox.Show("Images done.");
richTextBox1.AppendText("Fetching time information from log files..."+Environment.NewLine);
richTextBox1.Refresh();
int counter4Time = contentBathy.Length / 6;
//assign counter for lat,long and time
int timeCounter = 3;
for (int i = 0; i < counter4Time; i++)
{
richTextBox1.AppendText("Searching time match with image files..." + Environment.NewLine);
richTextBox1.Refresh();
double timeValue = Int32.Parse(contentBathy[timeCounter]);
//Looks for values that is +- 3 seconds different in the image file.
if (Array.Exists(imgTimeInfo, a => a == timeValue || a == timeValue + 1 || a == timeValue + 2|| a == timeValue+3
||a == timeValue-1|| a== timeValue-2||a == timeValue-3))
{
File.AppendAllText(#"c:\temp\matched.txt", "Lat : " + contentBathy[timeCounter - 3] + " Log : " + contentBathy[timeCounter - 2] + Environment.NewLine);
richTextBox1.AppendText("Image with same time information found. Looking for another match."+ Environment.NewLine);
}
else
{
//richTextBox1.AppendText("Time did not match...Writing GPX cordinates..." + Environment.NewLine);
//richTextBox1.Refresh();
File.AppendAllText(gpxLocation, "Lat : " + contentBathy[timeCounter - 3] + " Log : " + contentBathy[timeCounter - 2] + Environment.NewLine);
}
if(timeCounter < contentBathy.Length-3)
timeCounter += 6;
}
}
Lets say I have this loop and I put the data in an ArrayList:
int Num1 = Int32.Parse(textBox1.Text);
int Num2 = Int32.Parse(textBox2.Text);
ArrayList ItemList = new ArrayList();
while (Num1 <= Num2)
{
ItemList.Add(Num1);
Num1++;
}
And I have another loop to read my Arraylist:
foreach (int item in ItemList)
{
listBox1.Items.Add("Number " + item.ToString() + ",");
}
Which gives this result:
Number 1,
Number 2,
Number 3,
Number 4,
I need to remove the last comma in the last item and get this result:
Number 1,
Number 2,
Number 3,
Number 4
I've tried this:
foreach (int item in ItemList)
{
listBox1.Items.Add("Number " + item.ToString().Trim(',') + ",");
}
But it doesn't work. Can someone please tell me what I did wrong, and how I can fix it?
See if this works for your purposes:
var result = string.Join("," + Environment.NewLine, itemList.ToArray());
Forgot the "Number" part:
var result = string.Join(", " + Environment.NewLine, itemList.ToArray().Select(x => "Number " + x));
listBox1.Items.Add("Number " + item.ToString() +
ItemList.IndexOf(item) == ItemList.Count - 1 ? string.Empty : ",");
you should not modify the item of your collection inside a foreach.
May be you should try to modify your collection ItemList before the foreach that shows your result .
You can make somthing like this (before the foreach that shows your results):
ItemList[ItemList.Length-1] = ItemList[ItemList.Length-1].SubString(0,ItemList.Length -2);
How about this:
foreach (int item in ItemList)
{
if (listBoxOne.Items == null)
{
listBox1.Items.Add("Number " + item.ToString());
}
else
{
listBox1.Items.Add(",\n" + "Number " + item.ToString());
}
//Or more simply below
listBoxOne.Items.Add = listBoxOne.Items == null ? ("Number " + item.ToString()) : (",\n" + "Number " + item.ToString());
I have a DataGridView with four Columns and need to crate a multiline string from its content, separated by comma.
This code works, but probably - there is a more elegant way:
string multiLine = "";
string singleLine;
foreach (DataGridViewRow r in dgvSm.Rows)
{
if (!r.IsNewRow)
{
singleLine = r.Cells[0].Value.ToString() + ","
+ r.Cells[1].Value.ToString() + ","
+ r.Cells[2].Value.ToString() + ","
+ r.Cells[3].Value.ToString() + Environment.NewLine;
multiLine = multiLine + singleLine;
}
}
I don't know about elegant, but:
use StringBuilder for string manipulation, type string is immutable!
if you need to do something in between, separate first or last cycle running (e.g. comma separation)
So, basically something like this:
StringBuilder multiLine = new StringBuilder();
foreach (DataGridViewRow r in dgvSm.Rows)
{
if (!r.IsNewRow)
{
if (r.Cells.Count > 0)
{
multiLine.Append(r.Cells[0].Value.ToString()); //first separated
for (int i = 1; i < r.Cells.Count; ++i)
{
singleLine.Append(','); //between values
singleLine.Append(r.Cells[i].Value.ToString());
}
multiLine.AppendLine();
}
}
}
To illustrate speed difference between StringBuilder concatenation (just dynamic array of characters) and string (new object and copy everything each time you use operator + concatenation), have a look at mini-program:
public static void Main()
{
var sw = new Stopwatch();
sw.Start();
StringBuilder s = new StringBuilder();
//string s = "";
int i;
for (i = 0; sw.ElapsedMilliseconds < 1000; ++i)
//s += i.ToString();
s.Append(i.ToString());
sw.Stop();
Console.WriteLine("using version with type " + s.GetType().Name + " I did " +
i + " times of string concatenation.");
}
For my computer it is:
using version with type String I did 17682 times of string concatenation.
using version with type StringBuilder I did 366367 times of string concatenation.
Try this :
string multiLine = "";
string singleLine;
foreach (DataGridViewRow r in dgvSm.Rows)
{
if (!r.IsNewRow)
{
singleLine = r.Cells[0].Value.ToString() + ","
+ r.Cells[1].Value.ToString() + ","
+ r.Cells[2].Value.ToString() + ","
+ r.Cells[3].Value.ToString() + "\r\n";
multiLine = multiLine + singleLine;
}
}