I have many files in folder. and whenever there is any update in any file I Receive an event for that in my windows service application.
And I am looking for something by which I can validate the file with specific pattern. If it matches then only that file should be processed or else it should be ignored.
Something like this
if(File.Matches("genprice*.xml"))
{
DoSomething();
}
genprice20212604.xml
genprice20212704.xml
price20212604.xml
genprice20212704.txt
From above only #1 and #2 should be processed others should be ignored.
Your can try with regular expressions:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace ConsoleAppRegex
{
class Program
{
static void Main(string[] args)
{
string[] fileNames = new string[] { "genprice20212604.xml",
"genprice20212704.xml",
"price20212604.xml",
"genprice20212704.txt"};
Regex re = new Regex(#"genprice[^\.]*.xml");
foreach (string fileName in fileNames)
{
if (re.Match(fileName).Success)
{
Console.WriteLine(fileName);
}
}
Console.ReadLine();
}
}
}
I suggest to use Regex:
using System.Text.RegularExpressions;
using System.IO;
var reg = new Regex(#"genprice\d{8}$");
var fileNamesFromFolder = Direcotory.GetFiles(" #FolderĀ“s path ", "*.xml")
.Where(path => reg.IsMatch(Path.GetFileNameWithoutExtension(path)))
.Select(Folder=>
Path.GetFileNameWithoutExtension(Folder));
foreach (var file in fileNamesFromFolder )
{
//Do something...
}
Related
I'm trying to get a simple text parser class to work in VS2015. I received the class code and built a basic Console Application, added the class Cawk and tried to compile/run it.
The main error that I get is
Argument 1: cannot convert from 'string' to 'System.IO.StreamReader'
It's clear that I can't figure out how to pass a filename through Main to Cawk. How do I give it an argument of a filename?
Any help or pointers would be appreciated.
My Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main()
{
string input = #"c:\temp\test.txt";
Cawk.Execute(input);
}
}
}
Snippet of My Cawk.cs:
using System;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication3
{
public static class Cawk
{
public static IEnumerable<Dictionary<string, object>> Execute(StreamReader input)
{
Dictionary<string, object> row = new Dictionary<string, object>();
string line;
//string[] lines = File.ReadAllLines(path);
//read all rows
while ((line = input.ReadLine()) != null)
{
Execute accepts a StreamReader not a string.
Cawk.Execute(new StreamReader(#"c:\temp\test.txt"))
However, you should close the stream after you are done with it.
using (var sr = new StreamReader(#"c:\temp\test.txt"))
{
Cawk.Execute(sr);
}
something like:
var sr = new System.IO.StreamReader(#"c:\temp\test.txt");
Cawk.Execute(sr);
Simply use the File class from the System.IO namespace.
Cawk.Execute(File.OpenText(#"c:\temp\test.txt"));
Like this:
string input = #"c:\temp\test.txt";
Cawk.Execute(new System.IO.StreamReader(input));
You can put using System.IO; to the top like the rest of the usings, then you don't have to write it out later.
I am working on collecting urls from the web site in C# using WatiN framework. In my program it is fetching only one url. I don't know what is the problem. Any help will be appreciated.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WatiN.Core;
using WatiN.Core.Native.InternetExplorer;
namespace magicbricks
{
class scroll
{
[STAThread]
static void Main(string[] args)
{
Browser browserInstance;
browserInstance = new IE(#"http://www.99acres.com/property-in-chennai- ffid?search_type=QS&search_location=CP32&lstAcn=CP_R&lstAcnId=32&src=CLUSTER&isvoicesearch=N&keyword_suggest=chennai%20%28all%29%3B&fullSelectedSuggestions=chennai%20%28all%29&strEntityMap=W3sidHlwZSI6ImNpdHkifSx7IjEiOlsiY2hlbm5haSAoYWxsKSIsIkNJVFlfMzIsIFBSRUZFUkVOQ0VfUywgUkVTQ09NX1IiXX1d&texttypedtillsuggestion=chennai&refine_results=Y&Refine_Localities=Refine%20Localities&action=%2Fdo%2Fquicksearch%2Fsearch&suggestion=CITY_32%2C%20PREFERENCE_S%2C%20RESCOM_R");
foreach (var links in browserInstance.Links.Filter(Find.ByClass("b")))
{
Console.WriteLine(links.Url);
String filePath = "C:/Users/User/Desktop/New folder";
String fileName = "newop4.csv";
using (StreamWriter sr = new StreamWriter(Path.Combine(filePath, fileName), true))
{
sr.WriteLine(links.Url);
}
Console.ReadLine();
}
}
}
}
the above code prints only one url in the console.
Remove the Console.ReadLine(); As you are in a ForEach loop. If you still want the Console.ReadLine(); move it out the foreach
The Console.ReadLine(); waits for a user input, after you enter any value you should see the next URL.
I am getting all websites from localhost IIS manager 6 using DirectoryEntry class, I would like to get local path of each web application, but not sure how to get it, Is there anyway I can enumerate all properties of directory entry ?
DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
foreach (DirectoryEntry e in root.Children)
{
if (e.SchemaClassName == "IIsWebServer")
{
Console.WriteLine(e.Properties["ServerComment"].Value.ToString());
// how can I enumerate all properties and there values here ?
// maybe write to a xml document to find the local path property
I think you can use following code to find what you need. In case other questions just use the same approach. This code works for IIS6.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.DirectoryServices;
namespace IIS_6
{
class Program
{
static void Main(string[] args)
{
DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC");
string VirDirSchemaName = "IIsWebVirtualDir";
foreach (DirectoryEntry e in root.Children)
{
foreach (DirectoryEntry folderRoot in e.Children)
{
foreach (DirectoryEntry virtualDirectory in folderRoot.Children)
{
if (VirDirSchemaName == virtualDirectory.SchemaClassName)
{
Console.WriteLine(String.Format("\t\t{0} \t\t{1}", virtualDirectory.Name, virtualDirectory.Properties["Path"].Value));
}
}
}
}
}
}
}
With regards to IIS 7 I wrote this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// to add it from %windir%\System32\InetSrv\Microsoft.Web.Administration.dll
using Microsoft.Web.Administration;
namespace IIS_7
{
class Program
{
static void Main(string[] args)
{
using (ServerManager serverManager = new ServerManager())
{
foreach (var site in serverManager.Sites)
{
Console.WriteLine(String.Format("Site: {0}", site.Name));
foreach (var app in site.Applications)
{
var virtualRoot = app.VirtualDirectories.Where(v => v.Path == "/").Single();
Console.WriteLine(String.Format("\t\t{0} \t\t{1}", app.Path, virtualRoot.PhysicalPath));
}
}
}
}
}
}
i'm rather new and am trying to create a C# program that retrieves post from Facebook using FB API.
I have a word count feature which checks against a negative word dictionary.
This means that it would display the negative word along with its frequency occurrence.
The problem i'm facing now is that, i want to display the posts that contains this negative words. However, if the negative word exists 3 times in the post, the post would appear thrice. How do i solve this problem?
Below is my code:
(For designer)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace empTRUST
{
public partial class PostAnalysis : Form
{
DBStatusDL ad;
string target_fbid;
public PostAnalysis(string target_fbid)
{
InitializeComponent();
this.target_fbid = target_fbid;
ad = new DBStatusDL();
}
private void button_Displayposts_Click(object sender, EventArgs e)
{
int i = 1;
var dir = new DirectoryInfo(Application.StartupPath + "\\Dictionary"); //Load the dictionary from debug folder
var ed = new matchingWordsWithPosts();
var rows = ad.LoadStatus(target_fbid); //Call the load status function based on fb_id
foreach (FileInfo file in dir.GetFiles()) //For loop, to loop through files
{
var dict = File.ReadAllLines(dir.FullName + "\\" + file);
foreach (var row in rows)
{
List<DataRow> words = ed.countWordsInStatus(row, dict); // Retrieves word dictionary returned from function
foreach (var word in words)
{
var item = new ListViewItem(new[] { i.ToString() ,word["Status_message"].ToString(), word["Status_time"].ToString() });
listViewPosts.Items.Add(item);
i++;
}
}
}
}
private void button_Back_Click(object sender, EventArgs e)
{
this.Close();
var abc = new AnalysisPage(target_fbid);
abc.Show();
}
}
}
(For class)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
namespace empTRUST
{
class matchingWordsWithPosts
{
public List<DataRow> countWordsInStatus(DataRow status, string[] dictArray)
{
List<DataRow> statusList = new List<DataRow>();
var words = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase); // local word dictionary is created here
foreach (var dictEntry in dictArray)
{
var wordPattern = new Regex(#"\w+");
string smallDictEntry = dictEntry.ToLower();
foreach (Match match in wordPattern.Matches(status["Status_message"].ToString()))
{
if (match.ToString() == smallDictEntry)
{
statusList.Add(status);
}
}
}
return statusList; // returns local word dictionary to receiving end
}
}
}
Because you didn't provide the countWordsInStatus() function, I can't know if that's the problem. However, it looks like the problem is that that function continues going through a post even if it has already matched one such word. To fix this, you could put continue; (or perhaps a break;, depending on the code you're using) after adding a post to the list you're returning. This would have the loop skip to the next post, and make sure it doesn't continue counting words in the post that has already had a match.
If you post that function, it should be much easier to understand the issue.
After a word is matched and you process the post exit the loop.
The question that I have is regarding converting the process of reading lines from a text file into an array instead of just reading it.
The error in my codes appear at string[] lines = File.ReadLines("c:\\file.txt"); with cannot implicitly convert....
Can someone please advise on the codes to save the results in an array format? I've placed the ReadAllLines code which is able to save the results in an array too. Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace Testing
{
class Analysis
{
static void Main()
{
string[] lines = File.ReadLines("c:\\file.txt");
foreach (string r in lines)
{
Console.WriteLine("-- {0}", r);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
}
ReadAllLines Codes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace Testing
{
class ReadFromFile
{
static void Main()
{
string[] lines = System.IO.File.ReadAllLines
(#"C:\Users\Public\TestFolder\WriteLines2.txt");
System.Console.WriteLine("Contents of writeLines2.txt =:");
foreach (string line in lines)
{
Console.WriteLine("\t" + line);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
}
File.ReadLines() returns an object of type System.Collections.Generic.IEnumerable<String>
File.ReadAllLines() returns an array of strings.
If you want to use an array of strings you need to call the correct function.
You could use Jim solution, just use ReadAllLines() or you could change your return type.
This would also work:
System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("c:\\file.txt");
You can use any generic collection which implements IEnumerable, such as IList<String>.
string[] lines = File.ReadLines("c:\\file.txt").ToArray();
Although one wonders why you'll want to do that when ReadAllLines works just fine.
Or perhaps you just want to enumerate with the return value of File.ReadLines:
var lines = File.ReadLines("c:\\file.txt");
foreach (var line in lines)
{
Console.WriteLine("\t" + line);
}
Change string[] lines = File.ReadLines("c:\\file.txt"); to IEnumerable<string> lines = File.ReadLines("c:\\file.txt");
The rest of your code should work fine.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace FileReader
{
class Program
{
static void Main(string[] args)
{
var lines = File.ReadAllLines("D:/Text.txt").ToList();
if(lines != null && lines.Count > 0)
{
foreach(var line in lines)
{
Console.WriteLine(line);
}
}
Console.ReadKey();
}
}
}