Email alert sends email when lastwritetime is current [duplicate] - c#

I am trying to send an email when the lastwritetime is more than 16 minutes. I want to loop through my files and check lastwritetime. When more than 16 minutes old send an email alert. I am looking to use the local or system time where the images are stored. I have gotten this far, but the system emails too often and it does not alert when I run a test and the images have not updated. What am I doing wrong?
try
{
string files = #"\\cyclops-ch2-10\users\!SptEntEng\Desktop\ScreenScrapes\ChicagoSkyvision\ScreenScrape\ScreenScrape.png";
string files1 = #"\\cyclops-ch2-10\users\!SptEntEng\Desktop\ScreenScrapes\ChicagoSeachange\ScreenScrape\ScreenScrape.png";
string files2 = #"\\cyclops-ch2-10\users\!SptEntEng\Desktop\ScreenScrapes\IndianaSkyvision\ScreenScrape\ScreenScrape.png";
string files3 = #"\\cyclops-ch2-10\users\!SptEntEng\Desktop\ScreenScrapes\IndianaSeachange\ScreenScrape\ScreenScrape.png";
string files4 = #"\\cyclops-ch2-10\users\!SptEntEng\Desktop\ScreenScrapes\DetroitSkyvision\ScreenScrape\ScreenScrape.png";
string files5 = #"\\cyclops-ch2-10\users\!SptEntEng\Desktop\ScreenScrapes\MichiganSeachange\ScreenScrape\ScreenScrape.png";
string files6 = #"\\cyclops-ch2-10\users\!SptEntEng\Desktop\ScreenScrapes\LansingSkyvision\ScreenScrape\ScreenScrape.png";
string files7 = #"\\cyclops-ch2-10\users\!SptEntEng\Desktop\ScreenScrapes\MinnesotaSeachange\ScreenScrape\ScreenScrape.png";
string files8 = #"\\cyclops-ch2-10\users\!SptEntEng\Desktop\ScreenScrapes\HoustonSeachange\ScreenScrape\ScreenScrape.png";
var FilePaths = new List<string>();
FilePaths.Add(files);
FilePaths.Add(files1);
FilePaths.Add(files2);
FilePaths.Add(files3);
FilePaths.Add(files4);
FilePaths.Add(files5);
FilePaths.Add(files6);
FilePaths.Add(files7);
FilePaths.Add(files8);
foreach (string file in FilePaths)
{
FileInfo fi = new FileInfo("ScreenScrape.png");
if (fi.LastWriteTime < DateTime.Now.AddMinutes(16))
{
client.Send(CyclopsCentral);
break;
}
}

Your check will always be true as you are comparing to future time.
if (fi.LastWriteTime < DateTime.Now.AddMinutes(16))
You need to change it to -16
if (fi.LastWriteTime < DateTime.Now.AddMinutes(-16))

Related

How do I filter Directory.GetFiles() by a numeric range when file names are listed in numeric order?

I want filter which files are getting returned from the Directory.GetFiles() function. The files in the directory are all text files named with 6 digit numbers in incremental order (for example: "200501.txt", "200502.txt", "200503.txt", and so on), I would like to enter a "Starting Invoice Number" and "Ending Invoice Number" through 2 text box controls to return only the files within that range.
The current code is as follows...
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
string[] fileDir = Directory.GetFiles(fbd.SelectedPath);
string[] files = fileDir;
foreach (string loopfile in files)
{
int counter = 0;
string line;
//Gets invoice number from text file name
//This strips all unnecessary strings out of the directory and file name
//need to change substring 32 to depending directory using
string loopfileName = loopfile.Substring(32);
string InvoiceNumberLong = Path.GetFileName(loopfile);
string InvoiceNumber = InvoiceNumberLong.Substring(0,(InvoiceNumberLong.Length - 4)).ToString();
var controlCount = new List<string>();
var EndCount = new List<string>();
//Read through text file line by line to find all instances of "control" and "------" string
//adds all line position of these strings to lists
System.IO.StreamReader file = new System.IO.StreamReader(loopfile);
while ((line = file.ReadLine()) != null)
{
if (line.Contains("Control"))
{
controlCount.Add(counter.ToString());
}
if (line.Contains("------"))
{
EndCount.Add(counter.ToString());
}
counter++;
}
}
}
}
Thank you in advance!
You can't use the built in filter that the GetFiles method provides, that can only filter by wild cards. You can do it with some LINQ:
var files = Directory.EnumerateFiles(path, "*.txt")
.Where(d => int.TryParse(Path.GetFileNameWithoutExtension(d), out var value) && value > min && value < max);
Note: Using C#7 out var but can be converted to previous versions if you are not using the latest.

C# Reading newest file in directory

I't trying to get my program to read the most recent file in a directory with a few similar files and retrieve a name but its still reading all the files. If anyone knows why I'd appreciate the help :)
EDIT: Undo
here's my code:
public GetMyNames()
{
DirectoryInfo fileDirectory = new DirectoryInfo(#"C:\user\mark\folder");
List<string> files = new List<string>();
int creationDate = 0;
string CreationDate = "";
foreach (FileInfo fileInfo in fileDirectory.GetFiles("*.txt"))
{
string creationTime = fileInfo.CreationTime.ToString();
string[] bits = creationTime.Split('/', ':', ' ');
string i = bits[0] + bits[1] + bits[2];
int e = Int32.Parse(i);
if (e > creationDate)
{
creationDate = e;
files.Add(fileInfo.Name);
}
}
foreach(string file in files)
{
string filePath = fileDirectory + file;
string lines = ReadAllLines(filePath);
foreach (string line in Lines)
{
Name = Array.Find(dexLines,
element => element.StartsWith("Name", StringComparison.Ordinal));
}
MyName = Name[0];
}
Note that OrderBy runs at an order of O(nlog(n)) as it sorts the enumerable.
I suggest using Linq Max extension method, that is:
newestFile = files.Max(x => x.CreationDate);
this is more efficient (runs at an order of O(n)) and is more readable in my opinion
Why not use Linq and order by the date?
files.OrderBy(x => x.CreationDate)

Checklistbox to open files

I have created something that grabs all file names that have the extension .lua with them. This will then list them in a CheckListBox. Everything goes well there but I want to know which one of the CheckListBox's are ticked/checked and then open them in notepad.exe.
To dynamically add the files Code (works perfectly, and adds the files i want)
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = appData + "\\Lua";
string[] fileArray = Directory.GetFiles(path, "*.lua");
for (int i = 0; i < fileArray.Length; i++)
{
string Name = Path.GetFileName(fileArray[i]);
string PathToLua = fileArray[i];
ScriptsBoxBox.Items.AddRange(Name.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
Console.WriteLine(fileArray[i]);
}
Then when i check the items i want to open in notepad i use `
System.Diagnostics.Process.Start("notepad.exe", ScriptsBoxBox.CheckedItems.ToString());
Or
System.Diagnostics.Process.Start("notepad.exe", ScriptsBoxBox.CheckedItems);
Neither works and im pretty sure it's on my end. So my problem is that i cannot open the file that is ticked/checked in checklistbox and want to resolve this problem. However when I do
System.Diagnostics.Process.Start("notepad.exe", PathToLua);
It opens the files with .lua extension ticked or not which makes sense.
I don't think there are any arguments that you can pass to notepad to open a list of specific files. However, you can use a loop to open each file.
foreach (var file in ScriptsBoxBox.CheckedItems)
{
System.Diagnostics.Process.Start("notepad.exe", file);
}
I don't know WinForms as well as WPF but here goes
You need an object that contains your values
public class LuaFile
{
public string FileName { get; set; }
public string FilePath { get; set; }
public LuaFile(string name, string path)
{
FileName = name;
FilePath = path;
}
public override string ToString()
{
return FileName;
}
}
Replace your for loop with
foreach (var file in files)
{
ScriptsBoxBox.Items.Add(new LuaFile(Path.GetFileName(file), file));
}
And to run the checked files
foreach (var file in ScriptsBoxBox.CheckedItems)
{
System.Diagnostics.Process.Start("notepad.exe", ((LuaFile)file).FilePath);
}
Thanks everyone that helped but I solved it on my own (pretty easy when you read :P)
For anyone in the future that wants to do this here is how i accomplished it.
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = appData + "\\Lua";
string[] fileArray = Directory.GetFiles(path, "*.lua");
for (int i = 0; i < fileArray.Length; i++)
{
string Name = Path.GetFileName(fileArray[i]);
string PathToLua = fileArray[i];
//ScriptsBoxBox.Items.AddRange(Name.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
// Console.WriteLine();
Console.WriteLine(ScriptsBoxBox.CheckedItems.Contains(Name));
var pathname = ScriptsBoxBox.CheckedItems.Contains(Name);
if (ScriptsBoxBox.CheckedItems.Contains(Name))
{
System.Diagnostics.Process.Start("notepad.exe", fileArray[ScriptsBoxBox.CheckedItems.IndexOf(Name)]); // I supposed this would get the correct name index, and it did! fileArray by default seems to get the path of the file.
}

Search rasphone pbk file

In my application I'm using the rasphone function to connect to vpn's When my application launches it gets all the vpn connections in a combobox using this code.
String f = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\Microsoft\Network\Connections\Pbk\rasphone.pbk";
if (System.IO.File.Exists(f))
{
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
lines.Add(line);
}
}
foreach (string s in lines)
{
if (s.StartsWith("["))
{
char[] MyChar = { ']' };
string NewString = s.TrimEnd(MyChar);
char[] MyChar2 = { '[' };
string NewString2 = NewString.TrimStart(MyChar2);
comboBox1.Items.Add(NewString2);
}
}
}
else
{
MessageBox.Show("PBK File not found.");
}
comboBox1.Sorted = true;
Now my question is how I can also get the phonenumer= section to display in a textbox or label, so I know what the IP is.
A pbk file looks like this (had to delete some rows), the problem is that I have multiple vpn connections in the pbk file so also multiple phonenumer= entries.
[VPN Name of connection]
Encoding=1
PBVersion=3
Type=2
DEVICE=vpn
PhoneNumber= 0.0.0.0 <- ip address I want to display in a label or textbox.
AreaCode=
CountryCode=0
CountryID=0
UseDialingRules=0
Comment=
FriendlyName=
LastSelectedPhone=0
PromoteAlternates=0
TryNextAlternateOnFail=1
If you are looking for a very simple solution and I understand your question correctly this should do the trick, add the following statement after your current if in your foreach statement
else if(str.Contains("PhoneNumber"))
{
var x = str.Split('=');
if(x.Length > 1)
ip = x[1];
}
Please note that ip is the variable were you would like to store your IP-address.
To answer your question in the comments and assuming that you always have a [VPN-Connection] before each PhoneNumber entry you could write something like this
foreach (string s in lines)
{
if (s.StartsWith("["))
{
char[] MyChar = { ']' };
string NewString = s.TrimEnd(MyChar);
char[] MyChar2 = { '[' };
string NewString2 = NewString.TrimStart(MyChar2);
comboBox1.Items.Add(NewString2);
}
else if (s.Contains("PhoneNumber"))
{
string ip = comboBox1.Items[comboBox1.Items.Count - 1].ToString() + " : ";
var x = s.Split('=');
if (x.Length > 1)
ip += x[1];
}
}
This would get the item that were last added to the combobox and put it before the string of the ip address, still just a simple hack but it is one way to do it.. if you have more advanced needs I would make a class to store the data that you require and the populate the combobox from that.
well. you could read the file contents and use regex to extract it with
PhoneNumber=(?<ip>[^\n]+)
You can p/invoke RasGetEntryProperties passing it the pbk file, or you can simply parse out the value from the text file. Its in INI format and there are many INI File reader classes out there.

Permission error when accessing folder

I have created a web service to take all files found in a folder specified, eg C:/Incoming/20121018 and email them as attachments to an email address that I specify.
I can send a mail with one attachment successfully, but I thought I would pass several files via an array to be sent as attachments. The only problem is that when I try to read the folder containing the files, I get a Permission error, even though I have rights to that folder. Any idea on where I'm going wrong?
See my code below:
[WebMethod]
public string Sending_Email(string strEmailAddrFrom, string[] strEmailAddrTo, int intTotalEmailTo, string [] strAttachement)
{
DateTime LeadDate;
LeadDate = DateTime.Now.Date;
string Year = Convert.ToString(LeadDate.Year);
string Month = Convert.ToString(LeadDate.Month);
string Day = Convert.ToString(LeadDate.Day);
string[] arr1 = new string[150];
string Loc = "C:\\Incoming\\" + "" + Year + "" + Month + "" + Day + "";
StreamReader reader = File.OpenText(Loc);
string contents = reader.ReadToEnd();
reader.Close();
DirectoryInfo di = new DirectoryInfo(Loc);
FileInfo[] fileList = di.GetFiles(".*.");
int count = 0;
foreach (FileInfo fi in fileList)
{
arr1[count] = fi.Name;
}
EmailAlert NewMail = new EmailAlert();
return NewMail.EmailSent(strEmailAddrFrom, strEmailAddrTo, intTotalEmailTo, arr1);
}
your error lies here you are trying to open folder as stream which is not right way.
StreamReader reader = File.OpenText(Loc);
string contents = reader.ReadToEnd();
reader.Close();

Categories