I have Created a small XML tool, to find the numbers of element present in Multiple XML files.
This code gives the fine result for the elements which are must in XML files.
But when it comes to specific elements, which may be present or not in XML files, Software give me result as:
10/8/2012 11:27:51 AM
C:\Documents and Settings\AlaspuMK\Desktop\KS\success\4CPK-PMF0-004D-P565-00000-00.xml
Instance: 0
10/8/2012 11:27:51 AM
C:\Documents and Settings\AlaspuMK\Desktop\KS\success\4CPK-PMF0-004D-P566-00000-00.xml
Instance: 0
10/8/2012 11:27:51 AM
C:\Documents and Settings\AlaspuMK\Desktop\KS\success\4CPK-PMF0-004D-P567-00000-00.xml
Instance: 0
10/8/2012 11:27:51 AM
C:\Documents and Settings\AlaspuMK\Desktop\KS\success\4CPK-PMG0-004D-P001-00000-00.xml
**Instance: 11**
10/8/2012 11:27:51 AM
C:\Documents and Settings\AlaspuMK\Desktop\KS\success\4CPK-PMG0-004D-P002-00000-00.xml
Instance: 0
Now here the problem is XML files may be 500-1000 when i search the tag which may be present or not the tool gives me result for each and every files. In this case specific tag present instance may be 0 or multiple.
Can any one suggest the changes in my Code to find the file name in which instance is greater than 0. and if instance > 0 print it in text box.
My current code:
public void SearchMultipleTags()
{
if (txtSearchTag.Text != "")
{
try
{
//string str = null;
//XmlNodeList nodelist;
string folderPath = textBox2.Text;
DirectoryInfo di = new DirectoryInfo(folderPath);
FileInfo[] rgFiles = di.GetFiles("*.xml");
foreach (FileInfo fi in rgFiles)
{
int i = 0;
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(fi.FullName);
//rtbox2.Text = fi.FullName.ToString();
foreach (XmlNode node in xmldoc.GetElementsByTagName(txtSearchTag.Text))
{
i = i + 1;
//
}
rtbox2.Text += DateTime.Now + "\n" + fi.FullName + " \nInstance: " + i.ToString() + "\n\n";
//rtbox2.Text += fi.FullName + "instances: " + str.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("Invalid Path or Empty File name field.");
}
}
else
{
MessageBox.Show("Dont leave field blanks.");
}
}
If I understand correctly, you want to display text only if the i is greater than 0?
if(i > 0 )
rtbox2.Text += DateTime.Now + "\n" + fi.FullName + " \nInstance: " + i.ToString() + "\n\n";
Use
if(i > 0)
rtbox2.Text += DateTime.Now + "\n" + fi.FullName + " \nInstance: " + i.ToString() + "\n\n";
instead of simple
rtbox2.Text += DateTime.Now + "\n" + fi.FullName + " \nInstance: " + i.ToString() + "\n\n";
You could always just use this code inside the try block:
rtbox2.Text =
String.Join(Environment.NewLine + Environment.NewLine,
from fi in (new DirectoryInfo(textBox2.Text)).GetFiles("*.xml")
let xd = XDocument.Load(fi.FullName)
let i = xd.Descendants(txtSearchTag.Text).Count()
where i > 0
select String.Join(Environment.NewLine, new []
{
DateTime.Now.ToString(),
fi.FullName,
i.ToString(),
}));
Does it all in one line (bar the formatting). :-)
Related
I have data appended line by line in a text file for all confirmed transaction. I want to add Search functionality, where the user enters their E-mail address and all related transaction details connected to that E-mail must be displayed.
bool writeNextLine = false;
StringBuilder sb = new StringBuilder();
// Read the file and display it line by line.
using (System.IO.StreamReader file = new System.IO.StreamReader("record.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(txt_SearchBooking.Text))
{
// This append the text and a newline into the StringBuilder buffer
sb.AppendLine(line.ToString());
lbl_result.Text += sb.ToString();
}
}
}
but only the line containing Email is displayed other details are not.
Email is located on the last line of every transaction detail.
confirmmsg =
" Transaction # : " + EmployeeIDTextBox.Text + ClientIDTextBox.Text + UniqueIDTextBox.Text + "\r\n"
+ " First Name : " + ClientFirstNameTextBox.Text + "\r\n"
+ " Telephone Number : " + ClientTelephoneNumberTextBox.Text + "\r\n"
+ " Investment : " + investmentamt.ToString("C2") + "\r\n"
+ " Interest : " + (twelvemonthint * 100).ToString() + "%" + "\r\n"
+ " Interest Amount : " + (invesmentcalc(investmentamt, twelvemonthterm, twelvemonthint) - investmentamt).ToString("C2") + "\r\n"
+ " Bonus : " + bonus.ToString("c2") + "\r\n"
+ " Total Returns : " + invesmentcalc(investmentamt, twelvemonthterm, twelvemonthint).ToString("C2") + "\r\n"
+ " E-mail : " + ClientEmailTextBox.Text;
This is the data which is written into the text file.
If you always have 9 lines per transaction, with email being the last line, you could use File.ReadAllLines and a counter.
var lines = File.ReadAllLines("records.txt");
for(int i = 0; i < lines.Length; i++)
{
var line = lines[i];
if(line.Contains(txt_SearchBooking.Text))
{
//Retrieve the previous lines
for(int y = i-8; y <= i; y++)
{
lbl_result.Text += lines[y];
}
}
}
I'm provided with 2 Excel files that I convert to TSV files and in the end have to deliver in a TSV file. The 1st file is the main file (strWorksheetPath) and all lines have to be included. The 2nd file (PrintPath) has additional information but not each line in the main file has extra information. To do this in C# I followed this msdn guide to do what I have to do and it's working fine. Unfortunatly, file 1 has 23 columns and file 2 has 10 adding up to 33 columns and so 33 properties in total. I created some temp classes to see if everything is working but it looks very messy in my opinion.
Is there a way to clean up my code and make it look more tidy by possibly not having to make temp classes, condense some repetitive code, ...?
public static void ConvertTSVtoMontDataTable(string strWorksheetPath, string strPrintPath,
bool closeConnection = true)
{
// Check if the main file exist.
if (!File.Exists(strWorksheetPath)) return;
// Load both files.
var mainFile = File.ReadAllLines(strWorksheetPath);
var extraFile = File.ReadAllLines(strPrintPath);
// Create 2 lists.
var mainLines = mainFile.Select(line => new TempMainLine(line)).ToList();
var extraLines = extraFile.Select(line => new TempExtraLine(line)).ToList();
var lines = new List<TempLine>();
// Merge both files.
var leftOuterJoinQuery =
from worksheetLine in mainLines
join printLine in extraLines on string.Concat(worksheetLine.prop6, worksheetLine.prop8) equals
string.Concat(printLine.prop4, printLine.prop5) into lineGroup
from line in lineGroup.DefaultIfEmpty()
select
new TempLine(worksheetLine.prop0, worksheetLine.prop1, worksheetLine.prop2, worksheetLine.prop3,
worksheetLine.prop4, worksheetLine.prop5, worksheetLine.prop6, worksheetLine.prop7,
worksheetLine.prop8, worksheetLine.prop9, worksheetLine.prop10, worksheetLine.prop11,
worksheetLine.prop12, worksheetLine.prop13, worksheetLine.prop14, worksheetLine.prop15,
worksheetLine.prop16, worksheetLine.prop17, worksheetLine.prop18, worksheetLine.prop19,
worksheetLine.prop20, worksheetLine.prop21, worksheetLine.prop22, line == null ? "" : line.prop0,
line == null ? "" : line.prop1, line == null ? "" : line.prop2, line == null ? "" : line.prop3,
line == null ? "" : line.prop4, line == null ? "" : line.prop5, line == null ? "" : line.prop6,
line == null ? "" : line.prop7, line == null ? "" : line.prop8, line == null ? "" : line.prop9);
foreach (var tempLine in leftOuterJoinQuery)
{
lines.Add(tempLine);
}
// Write output to new temp file (TESTING)
using (
var file =
new StreamWriter(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"output.txt")))
{
foreach (var item in lines)
{
file.WriteLine(item.prop0 + (char)9 + item.prop1 + (char)9 + item.prop2 + (char)9 + item.prop3 +
(char)9 + item.prop4 + (char)9 + item.prop5 + (char)9 + item.prop6 + (char)9 +
item.prop7 + (char)9 + item.prop8 + (char)9 + item.prop9 + (char)9 + item.prop10 +
(char)9 + item.prop11 + (char)9 + item.prop12 + (char)9 + item.prop13 + (char)9 +
item.prop14 + (char)9 + item.prop15 + (char)9 + item.prop16 + (char)9 +
item.prop17 + (char)9 + item.prop18 + (char)9 + item.prop19 + (char)9 +
item.prop20 + (char)9 + item.prop21 + (char)9 + item.prop22 + (char)9 +
item.prop23 + (char)9 + item.prop24 + (char)9 + item.prop25 + (char)9 +
item.prop26 + (char)9 + item.prop27 + (char)9 + item.prop28 + (char)9 +
item.prop29 + (char)9 + item.prop30 + (char)9 + item.prop31 + (char)9 +
item.prop32);
}
}
}
I thought about this some more and regardless of what your Temp* classes look like, something along the lines of the below will work given the assumption that (based on the code you presented), you're outputting every column from both files in the order in which they came in. If you needed to exclude fields, change the order, etc., that would require some changes to the below or a different solution entirely.
It's basically just reading those two files in, joining on the Split() result and then combining the two lines. I didn't see a point in handling the LOJ logic for a null printFile line but if you need the extra tabs, you could replace the line ?? "" with something like line ?? new String('\t', 10)
Note that this is probably not the most efficient way to go about this and if your files are huge, you'd definitely want to optimize this a bit.
// Merge both files.
var lines =
from worksheetLine in mainFile
join printLine in extraFile on string.Concat(worksheetLine.Split('\t')[6], worksheetLine.Split('\t')[8]) equals
string.Concat(printLine.Split('\t')[4], printLine.Split('\t')[5]) into lineGroup
from line in lineGroup.DefaultIfEmpty()
select string.Concat(worksheetLine, line ?? "");
// Write output to new temp file (TESTING)
using (
var file =
new StreamWriter(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"output.txt")))
{
foreach (var item in lines)
{
file.WriteLine(item);
}
}
I am creating application to delete files for more than 15 days in past, I've created a project using the C# language "multithreading" to be able to delete these files, but its only reading the first file with the error
The directory name is invalid
Can anyone help me on this please?
private void process3()
{
//DirectoryInfo info1 = new DirectoryInfo(#"\\10.4.9.202\d\PapyrusRes\appdata\");
DirectoryInfo info1 = new DirectoryInfo(#"\\DXB-RASO-MCH\Users\oalahmad\Dropbox\backup\Backup5\Desktop\New folder2");
// long Size = 0;
//C:\Users\oalahmad\Dropbox\backup\Backup5\Desktop\New folder2
String[] filePaths = (from fls in info1.EnumerateFiles()
where (fls.LastWriteTime.Date < DateTime.Today.AddDays(-15))
select fls.FullName).ToArray();
int i = 0;
if (!File.Exists(logPath3))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(logPath3))
{
sw.WriteLine("Deletion Process History:");
sw.WriteLine(" ");
sw.WriteLine(" ");
}
}
//stopwatch.Start();
try
{
foreach (String f in filePaths)
{
DirectoryInfo info = new DirectoryInfo(f);
int difference = DateTime.Today.Subtract(info.LastWriteTime).Days;
textBox2.BeginInvoke(new Action(() =>
{
textBox2.Text += "Folder Name: " + Path.GetFileName(f) +
"\r\nDate Modified: " + difference +
"\r\n------\r\n";
}));
Thread.Sleep(10);
i++;
Directory.Delete(f, true);
count++;
}
using (StreamWriter sw = File.AppendText(logPath3))
{
sw.WriteLine("Successful at: " + DateTime.Now + " " + count +
" files were deleted");
}
}
catch (Exception ex)
{
// log errors
// Write your content here
using (StreamWriter sw = File.AppendText(logPath3))
{
if (count == 0)
sw.WriteLine("Unsuccessful at: " + DateTime.Now + " Error: " +
ex.Message);
else
sw.WriteLine("Unsuccessful at: " + DateTime.Now + " " + count +
" files were deleted" + " Error: " + ex.Message);
}
}
}
I'm writing a application that reads Ia directory contents and writes that to a csv file. I'm trying to get a list of certain file extensions from and upload path which contains a csv file and write a list of the filtered extensions to a new csv file.
I cant figure out how to get the filtered csv file written.....
Here's my method.
StringBuilder CreateUserFileUploadList(SLDocument document, StringBuilder destroyWorksheet)
{
document.SelectWorksheet("User Folder");
var stats = document.GetWorksheetStatistics();
var rowcount = stats.EndRowIndex + 1;
List unwantedExtensions = cblExtensions.Items.Cast().Where(li => li.Selected).Select(li => li.Text).ToList();
if (!String.IsNullOrEmpty(tbOtherExtensions.Text))
{
unwantedExtensions.AddRange(tbOtherExtensions.Text.ToUpper().Split(new char[] { ',', ' ', '.' }, StringSplitOptions.RemoveEmptyEntries));
}
unwantedExtensions.AddRange("EXE,COM,BAT,JS,VBS,PIF,CMD,DLL,OCX,PWL".Split(new char[] { ',', ' ', '.' }, StringSplitOptions.RemoveEmptyEntries));
// new CSV file
var workSheet = new StringBuilder();
workSheet.AppendLine("FILEPATH,Client,Matter,LAST MODIFIED DATE,CREATED DATE,CREATED BY,LAST MODIFIED BY,FOLDER,DOCUMENT NAME,Author,Practice Area,Document Type,ACCESS,Keywords - Comments");
// loop through the directories
for (int i = 2; i 100 chars, or including TAB / \ : * ? " |
// Folder has folders>500 or has files>1000
//TODO: this loops through leaf folders; we need to check intermediate folders to ensure they don't have too many files or folders or a bad name
//Took out #"\",
bool invalidFolderName = new string[] { "/", ":", "*", "?", "" }.Any(s => directoryName.Contains(s));
if (invalidFolderName || directoryName.Length > 200 || files.Count() > 1000)
{
System.Diagnostics.Debug.WriteLine("INVALID folder: " + directoryName);
lblError.Text = lblError.Text + "\r\n" + "INVALID folder: " + directoryName;
//TODO: This should cause the WHOLE upload to fail
}
// build the target folder path
string folder;
string[] stringSeparators = new string[] { tbAuthor.Text };
var path = directoryName.Split(stringSeparators, StringSplitOptions.None);
folder = path.Last();
if (path.Count() > 1)
{
folder = ConfigurationManager.AppSettings["NetDocumentsFolderPath"].ToString() + tbAuthor.Text + #"\User Folder" + folder;
if (folder.Substring(folder.Length - 1, 1) == #"\")
{
folder = folder.Substring(0, folder.Length - 1);
}
}
// Get the files
foreach (var file in files)
{
// Remove unwanted extensions
if (!unwantedExtensions.Contains(file.Extension.Replace(".", "").ToUpper()))
{
var access = file.GetAccessControl();
string user = access.GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
//TODO: FWIW, fileName (on netdocs) does NOT need to match the name in the original location...
string fullName = file.FullName;
string fileName = file.Name;
// Wrap in quotes if there are any invalid characters
if (fullName.IndexOfAny(csvTokens) >= 0)
{
fullName = "\"" + fullName.Replace("\"", "\"\"") + "\"";
}
if (fileName.IndexOfAny(csvTokens) >= 0)
{
fileName = "\"" + fileName.Replace("\"", "\"\"") + "\"";
}
if (!document.GetCellValueAsString(i, 2).ToUpper().Contains("DESTROY"))
{
String practiceArea = GetPracticeAreaForClientMatter(document.GetCellValueAsString(i, 2), document.GetCellValueAsString(i, 3));
String documentType = ConfigurationManager.AppSettings["FileDocumentType"].ToString();
// Validate file
// Invalid file names (>200 chars, or TAB / \ : * ? " |
// Invalid file size (>200 MB)
bool invalidFileName = new string[] { "/", #"\", ":", "*", "?", "" }.Any(s => file.Name.Contains(s));
if (invalidFileName || file.Length > 200000000 || file.Name.Length > 200)
{
System.Diagnostics.Debug.WriteLine("INVALID file: " + file.Name);
lblError.Text = lblError.Text + "\r\n" + "INVALID file: " + file.Name;
//TODO: This should cause the WHOLE upload to fail
}
else
{
workSheet.AppendLine(
fullName + "," +
document.GetCellValueAsString(i, 2) + "," +
document.GetCellValueAsString(i, 3) + "," +
file.LastWriteTime + "," +
file.CreationTime + "," +
tbAuthor.Text + "," +
tbAuthor.Text + "," +
folder + "," +
fileName + "," +
tbAuthor.Text + "," +
practiceArea + "," +
documentType + "," +
practiceArea + "|V," +
"Imported from Departed Attorney on: " + DateTime.Now.ToString("G"));
}
}
else
{
destroyWorksheet.AppendLine(fullName);
}
}
}
}
bool invalidFileName = new string[] { "/", #"\", ":", "*", "?", "" }.Any(s => file.Name.Contains(s));
if (document.GetCellValueAsString(i, 2).ToUpper().Contains("DESTROY"))
{// Files in folders marked "destroy" are saved elsewhere
//destroyWorkSheet.Append(string.Format("{0}", "Directory" + fullName));
//destroyWorkSheet.Append(string.Format("{1}", "FileName" + fullName));
// destroyWorkSheet.AppendLine("Directory, FileName");
// destroyWorkSheet.Append(string.Format("{0},{1}", "Directory", "FileName") + fullName);
destroyWorksheet.AppendLine(fullName);
}
// Validate file for name (less than 200 chars, can't have TAB / \ : * ? " | ) and size ( less than 200 MB)
else if (invalidFileName || file.Length > 200000000 || file.Name.Length > 200)
{// This should cause the WHOLE upload to fail
System.Diagnostics.Debug.WriteLine("INVALID file: " + file.Name);
lblError.Text = lblError.Text + "\r\n" + "INVALID file: " + file.Name;
errorWorksheet.AppendLine("INVALID file: " + file.Name);
}
else if (unwantedExtensions.Contains(file.Extension.Replace(".", "").ToUpper()))
{// Files with unwanted extensions are filtered out
filterWorksheet.AppendLine(fullName);
}
I am using c# windows application to get data from database and display on datagridview and exporting to text file
I want to remove empty spaces between below 4 columns .
2
vehicle control services ltd
Brom
Malkit
i get 2 vehicle control services ltd brom mal, but i want it to be like 2vehicle control services ltdBromMlkit
this is my code.
string stringSql = " SELECT distinct " +
"'" + comboBox6.Text + "' as RecordType" +
" , left([Claimant Name] +' ',30) " +
" , left([Claimant Address1] +' ',30) " +
" , left([Claimant Address2] +' ',30) as ClaimantAddress2 " +
" , left([Claimant Address3] +' ',30) as
exporting to text file code
if (obj == null || obj == Convert.DBNull)
return "";
// if string has no ','
if (obj.ToString().IndexOf(",") == -1)
return obj.ToString();
// remove backslahes
return "\"" + obj.ToString() + "\"";
}
private void ExportDatatviewToCsv(string iFilename, DataView dv)
{
// Open output stream
StreamWriter swFile = new StreamWriter(iFilename);
// Rows of Data
foreach (DataRowView rowData in dv)
{
string[] colData = new string[dv.Table.Columns.Count];
for (int i = 0; i < dv.Table.Columns.Count; i++)
{
object obj = rowData[i];
colData[i] = GetWriteableValueForCsv(obj);
}
// Write data in row
swFile.WriteLine(string.Join(" ", colData));
}
// Close output stream
swFile.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
if (myDataset == null)
{
return;
}
if (myDataset.Tables[0].Rows.Count == 0)
{
return;
}
DataView vwExport = new DataView(myDataset.Tables[0]);
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "TXT file|*.txt";
sfd.FileName = "ee " + ".txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
if (sfd.FileName != "")
{
ExportDatatviewToCsv(sfd.FileName, vwExport);
MessageBox.Show("File has been saved as: " + Environment.NewLine + sfd.FileName + Environment.NewLine + Environment.NewLine + "NB: This dataset has been ordered by t_reference in ascending order. If being combined with an existing dataset - that dataset will also need to be sorted in this way.", "Operation complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Just to make it clear what I think you are asking...
You currently get this for each line:
2 vehicle control services ltd brom mal
but you want it like this for each line (which let me point out makes absolutely no sense at all, it doesn't look very usable):
2vehicle control services ltdBromMlkit
If that is the case then in your code just replace this line:
swFile.WriteLine(string.Join(" ", colData));
with this line:
swFile.WriteLine(string.Join("", colData));
Notice that it will now join the string with an empty string, rather than joining with the single space that you don't want.