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]);
}
}
Related
I have a dropdownlist in a view like this,
<style type="text/css">
.form-control {
width: 50%;
padding: 10px;
}
#Html.DropDownListFor(x => x.FileName, ((IEnumerable<SelectListItem>)ViewData["Items"]), new { size = 15, #class = "form-control" , #style = "padding: 10px;"})
#Html.ValidationMessageFor(x => x.FileName)
The values look like below,
aaa.txt (2015-01-01) (0 B)
abcdedfff.txt (2015-02-01) (17 MB)
I want to add some spaces between these items so that it would look like below,
aaa.txt (2015-01-01) (0 B)
abcdedfff.txt (2015-02-01) (17 MB)
The controller has below code,
if (Directory.Exists(path))
{
files = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)
.Select(Path.GetFileName).OrderBy(f => f).ToArray();
}
long fSize = 0;
var count = 0;
var fileModified = "";
string fileSize = "";
string[] sizes = { "B", "KB", "MB", "GB" };
foreach (var filename in files)
{
var fileInfo = new FileInfo(path + "\\" + filename);
fSize = fileInfo.Length;
int order = 0;
while (fSize >= 1024 && order + 1 < sizes.Length)
{
order++;
fSize = fSize / 1024;
}
fileSize = String.Format("{0:0.##} {1}", fSize, sizes[order]);
fileModified = fileInfo.LastWriteTime.ToString("yyyy-MM-dd hh:mm:ss tt");
SelectListItem file = new SelectListItem() { Value = count.ToString(), Text = filename + " ( " + fileModified + " )" + " ( " + fileSize + " )" };
fileItems.Add(file);
count++;
}
How do I do that?
That's a lot of code to go into one of your Controller's methods. I would create different classes, maybe as services, that do all of that work for you.
I think the only way to do this is to create a service that creates the space for you.
You can modify the code you already have to create the space you want, or you can create another class that does it for you.
public class SelectListService
{
public IEnumerable<SelectListItem> GetData()
{
// Get your data
// create your spacing
// return your formatted SelectList
}
}
Then in your controller you just have to...
var selectListService = new SelectListService();
fileItems = selectListService.GetData();
Then of course pass it into your View however you're already doing it.
I think you have to get the highest length of your filename in your collection and than use right padding and space as padding character to your filename.
Try :
if (Directory.Exists(path))
{
files = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)
.Select(Path.GetFileName).OrderBy(f => f).ToArray();
}
long fSize = 0;
var count = 0;
var fileModified = "";
string fileSize = "";
string[] sizes = { "B", "KB", "MB", "GB" };
int longest_file_length = files.Max(a => a.Length);
foreach (var filename in files)
{
var fileInfo = new FileInfo(path + "\\" + filename);
fSize = fileInfo.Length;
int order = 0;
while (fSize >= 1024 && order + 1 < sizes.Length)
{
order++;
fSize = fSize / 1024;
}
fileSize = String.Format("{0:0.##} {1}", fSize, sizes[order]);
fileModified = fileInfo.LastWriteTime.ToString("yyyy-MM-dd hh:mm:ss tt");
string padded_file_name = filename.PadRight(longest_file_length, ' ');
SelectListItem file = new SelectListItem() { Value = count.ToString(), Text = padded_file_name + " ( " + fileModified + " )" + " ( " + fileSize + " )" };
fileItems.Add(file);
count++;
}
Also, you have to use monospace font so that the width of each character is same.
{ font-family:"Courier New", Courier, monospace; }
You could try alignment with String.Format like below:
SelectListItem file = new SelectListItem() { Value = count.ToString(), Text = String.Format("{0,-25} ({1}) ({2})", filename, fileModified, fileSize) };
You can see example at this link and read more about string formatting here.
Here is how you should modify your method if you want deservable output:
var maxFileNameLength = files.Max(x => x.Length);
foreach (var filename in files)
{
var fileInfo = new FileInfo(path + "\\" + filename);
fSize = fileInfo.Length;
int order = 0;
while (fSize >= 1024 && order + 1 < sizes.Length)
{
order++;
fSize = fSize / 1024;
}
fileSize = String.Format("{0:0.##} {1}", fSize, sizes[order]);
fileModified = fileInfo.LastWriteTime.ToString("yyyy-MM-dd hh:mm:ss tt");
fileNameWithSpaces = filename + string.Concat(Enumerable.Repeat(" ", maxFileNameLength + 1 - filename.Length));
SelectListItem file = new SelectListItem() { Value = count.ToString(), Text = fileNameWithSpaces + " ( " + fileModified + " )" + " ( " + fileSize + " )" };
fileItems.Add(file);
count++;
}
Ok, i check it. If you want to show your spaces in drop down you should use rather that space. I updated the code
how about something like this
$("#selectId > option").each(function() {
var thistext=$(this).text();
var brindex=thistext.indexOf('(');
var firststring=thistext.substr(0,brindex)+" ";
var laststring=thistext.substr(brindex,thistext.length);
$(this).text(firsstring+laststring);
});
not tested but it should work
I am trying to build a console application using Web Services. Its use 2 functions. The first one GetAllProject outputs ptojectsID and ProjectsNames.
The second function is GetUsersList and it outputs the list of users. Its need as a mandatory parameter the projectID which has been requested by calling the first function.
What I would like to do its to output into a CSV file the projectID, the projectName and the totals of userIDs.
When I run the console, it worked fine but in the column for the totals of userIDs I gets as an output System.String[].
I don't know what I could do to instead of extracting on each line System.String[] the actual total of usersIDs corresponding to each projectID
I don't know how to achieve this. Here you have my code.
string outCsvFile = string.Format(#"C:\\test\\test.csv");
WS.Projects[] pr = db.GetAllProject();
using (StreamWriter file = new StreamWriter(outCsvFile))
{
for (int i = 0; i < pr.Length; ++i)
{
string[] subecjtsIDS = new string[] {""};
subecjtsIDS = db.GetUsersList(pr[i].ProjectID);
file.WriteLine(pr[i].ProjectID + ',' + pr[i].ProjectTitle + ',' + subecjtsIDS);
}
}
If I'm correctly interpreting your requirements, you're not trying to sum the user IDs (which wouldn't make sense), you're just trying to list them as part of a CSV row. Assuming that's correct...
The problem is that this line
file.WriteLine(pr[i].ProjectID + ',' + pr[i].ProjectTitle + ',' + subecjtsIDS);
Is attempting to concatenate a string array onto a string. To do this, .NET will call the array's .ToString() method, and, for most reference types in the framework, this just prints the name of the type, i.e. "System.String[]".
Instead, you need to iterate the array and print its contents. The String class provides a nice way to do this: the Join() method:
file.WriteLine(pr[i].ProjectID + ',' + pr[i].ProjectTitle + ',' + String.Join(",", subecjtsIDS));
If, however, you're trying to add the number of subjects associated with each project to each line, you just want the Length of the array:
file.WriteLine(pr[i].ProjectID + ',' + pr[i].ProjectTitle + ',' + subecjtsIDS.Length);
Try this
using (StreamWriter file = new StreamWriter(outCsvFile))
{
for (int i = 0; i < pr.Length; ++i)
{
string[] subecjtsIDS = new string[] {""};
subecjtsIDS = db.GetUsersList(pr[i].ProjectID);
foreach(var id in subecjtsIDS)
{
file.WriteLine(pr[i].ProjectID + ',' + pr[i].ProjectTitle + ',' + id );
}
}
}
This will write more rows but if you use string.Join("," subecjtsIDS) then the number of columns increased and your data will become very complex to understand.
You are going to need to loop through that array and create a string where the values are comma-separated (or whatever it is you want as output). For example:
string outCsvFile = string.Format(#"C:\\test\\test.csv");
WS.Projects[] pr = db.GetAllProject();
using (StreamWriter file = new StreamWriter(outCsvFile))
{
for (int i = 0; i < pr.Length; ++i)
{
string[] subecjtsIDS = new string[] {""};
subecjtsIDS = db.GetUsersList(pr[i].ProjectID);
string formattedSubecjtsIDs;
for (int j = 0; j < subecjtsIDs.length; j++)
{
if (!string.IsNullOrEmpty(formattedSubecjtsIDs))
formattedSubecjtsIDs += ", ";
formattedSubecjtsIDs += subecjtsIDs[j];
}
file.WriteLine(pr[i].ProjectID + ',' + pr[i].ProjectTitle + ',' + formattedSubecjtsIDS);
}
}
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);
I was wondering if you cloud help me?
I have an array that consist of items and prices and qty.
If the item exist it the array it must update the price and the qty, If it doesn't exits it must be added
Here is my code that i have tried:
if (line.Contains(ItemCode))
{
string[] details = line.Split(new string[] { "|" }, StringSplitOptions.None);
{
for (int i = 0; i < details.Length; i++)
{
if (details[i].Contains(ItemCode))
{
string[] line_details = details[i].Split(',');
string replace = line_details[2].Trim() + "," + line_details[3].Trim();
double NewQty = double.Parse(Qty) + double.Parse(line_details[2]);
double NewPrice = (double.Parse(UnitPrice) * double.Parse(Qty));
double NewUnitPrice = NewPrice + double.Parse(line_details[3]);
string new_replace = NewQty + "," + NewUnitPrice;
line = line.Replace(replace, new_replace);
}
}
}
}
else
{
line = line + "\"Detail\",0," + Qty + "," + (double.Parse(UnitPrice) * double.Parse(Qty)) + "," + InclusivePrice + ",\"" + UnitUsed + "\"," + TaxType + "," + DiscountType + "," + DiscountPercentage + ",\"" + ItemCode + "\",\"" + Description + "\"," + SearchType + "," + "\"\"" + ",\"" + MultiStore + "\"|" + Environment.NewLine;
}
it is not working could you maby assist me on this?
Arrays in C# cannot have entries added to them after being initialised. You're better off using a List<String> instead, where you can add and remove entries from the list. Alternatively consider a Dictionary<Int32, String>, which would let you use the ItemCode as an identifier to make finding a given entry easier.
As a furthur point, instead of storing all your item data in a delimited string, make a new Class for them, with the various details as properties, and then you can use a theoretical Dictionary<Int32, ItemObject> for better clarity.
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;
}
}