C# IF Else loop - c#

I want to create a c# program that will look in a folder for files. If the files are found then I want to start a program. If the file is not there then I want to program to sleep for 30 minutes and look in the folder again. I want to keep doing it maybe 10 times and if it still doesn’t find the file then exit the program. I wrote the if part but I need help on the else part. This is what I have so far.
using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Diagnostics;
class Program
{
static void Main()
{
// See if this file exists in the SAME DIRECTORY.
if (File.Exists(#"C:\name.txt"))
{
Process.Start(#"C:\bulkload.bat");
}
else
{
}
}
}

Untested, for guidance purpose only.
for (int i = 0; i < 10; i++)
{
if (File.Exists(#"C:\name.txt"))
{
Process.Start(#"C:\bulkload.bat");
return;
}
else //no need of else block really.
{
Thread.Sleep(30 * 60 * 1000);
}
}

Related

inserting into index location of a text file if a string does exist inside the line, if the string doesn't exist, still write line as it was

The program is supposed to look for a string in a line, and if it finds the string, it will make the inserts after meeting the condition inside the textfile. Currently, when I run this program it is now simply giving me a blank console. Previously, I had it just reading all the lines properly and could make inserts only if I remove them first but it messed the indexing up and ultimately did not give me the result I wanted. The logic is fairly straightforward, if you see any problems please share your thoughts. Please and thanks. I am very confused why this is having problems and not working.
using System.IO;
using System.Globalization;
using System.Diagnostics;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
namespace Masker
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine();
string path = #"\file1.txt";
ReadLines(path)
}
public static void ReadLines(string path)
{
int counter = 0;
var text = new StringBuilder();
foreach (string s in File.ReadAllLines(path))
{
counter += 1;
if (s.Contains("000INDEX"))
{
text.AppendLine(s.Insert(60, "#"));
}
else if (s.Contains("001PRTBNR"))
{
text.AppendLine(s.Insert(60, "#").Insert(119,"#").Insert(120,"#").Insert(121, "#"));
};
text.AppendLine(s);
//Console.Write(text.ToString());
}
Console.Write(text.ToString());
}
}
}
The last two blocks of your if/else statement will never be executed.
If the execution reaches the third check
else if (s.Contains("000INDEX"))
that will always be true. Because if it wasn't, then the first check
if (!s.Contains("000INDEX"))
would have already been true.
But the biggest problem is that if the line contains "000INDEX", your while loop becomes and infinite loop. You never leave it. That is probably the reason why you end up with a blank console.

Webclient.DownloadFileCompleted event failed

I am downloading a large file from a web site.
Size: = 599 MB (629,113,799 bytes).
The program works fine.
However I run into some errors:
not able to validate that the file was completely donwloaded.
I did not see any of the messages in the screen that says
Console.WriteLine("..............File succesfully downloaded......This mesage comes from -- wc_DownloadFileCompleted..........");
So the program does download the file completely.
(I did download the file manually using the web browser and compared the
file size between the manual download and the file that was downloaded
via the program. The size was the same. So that is a good reason for me
to believe that the program did download the file completely)
However at the very end (after it displays the percentage as 99)
it throws an error.. Here is the message
An exception occured during a WebClient request.
The error message gets fired inside the wc_DownloadFileCompleted
method.
So the help I need is... How do we validate that the file was downloaded
completely (without any errors)? Also how do we eliminate the error.
Is there some other code that I can use instead of using the code
I presented.
I did see the File Download percentage 99 appear in the screen.
However I did not see the "100" appear. Any comments?
using System.Threading.Tasks;
using System;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Reflection; //Need this to get the DEBUG path
using MHPUtil;
using System.Net;
using System.Globalization;
namespace CmsNpiFileLoad
{
public static class FileDownLoadPercentage
{
//We need a global variable that will remain the same throughout the run.
//The unique value for this variable will get set in the DownloadFile() method.
public static string Value { get; set; }
}
class CMsNPIFileDownLoad
{
//599 MB (629,113,799 bytes) is the size of the file.
public void DownloadCMSNPIFile()
{
string Destinationfile = "S:\\MIS\\Provider NPI file\\" + "NPI.zip";
string CmsDownLoadSite = "http://download.cms.gov/nppes/NPPES_Data_Dissemination_January_2018.zip";
//Is the INTERNET AVAILABLE
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
Console.WriteLine("Internet available, proceed with the download");
}
else
{
Console.WriteLine("Internet not available, proceed with the download");
return;
}
//So at this point we dont have that file with us locally.. so lets download
Console.WriteLine("Start Downloading....");
try
{
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += wc_DownloadProgressChanged; // This works well
client.DownloadFileCompleted += wc_DownloadFileCompleted;
client.DownloadFileAsync(new System.Uri(CmsDownLoadSite), Destinationfile);
}
}
catch (WebException we)
{
Console.WriteLine(we.ToString());
}
Console.ReadLine(); // We dont want the black screen to just disapper from us. so we put a readline so that it will keep displaying all the messsages
}
private static void wc_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Cancelled)
{
Console.WriteLine("The download has been cancelled");
return;
}
if (e.Error != null)
{
//I tested the the program 2 times.. each time an error occured.
//The error message is "An exceptipon occured during a WebClient request.
Console.WriteLine("An error ocurred while trying to download file");
Console.WriteLine(e.Error.Message.ToString());
return;
}
// I did not see this on the screen.. ????
Console.WriteLine("..............File succesfully downloaded......This mesage comes from -- wc_DownloadFileCompleted..........");
}
private static void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
if (FileDownLoadPercentage.Value != e.ProgressPercentage.ToString())
{
FileDownLoadPercentage.Value = e.ProgressPercentage.ToString();
//Display File Donwload Percentage ( increments of 10 )
if (Convert.ToInt16(e.ProgressPercentage) % 10 == 0)
Console.WriteLine(e.ProgressPercentage.ToString());
//Show the percentage when it is 99
if (Convert.ToInt16(e.ProgressPercentage) == 99)
Console.WriteLine(e.ProgressPercentage.ToString());
}
if (e.BytesReceived == e.TotalBytesToReceive)
{
Console.WriteLine("File DownLoad Complete...This message comes from -- wc_DownloadProgressChanged "); // I did not see this on the screen.. ????
}
}
}
}

Copy code to clipboard on build in Visual studio

I have an unusual situation here.
Problem
I'm using Visual studio (VS) to write scripts to use in-game in the game Space Engineers.
The problem is that you only use a portion of the code from the file in-game. (I.E, Ctrl+A wont do). So selecting the correct portion is tedious.
I want to streamline the process of copying the desired code in VS and pasting it in Space Engineers.
The idea is to trim all unnecessary white space (there's a character limit) and copy to clipboard when pressing run in VS.
Where I'm at
I've found that you can make your own build configuration and use the "Pre-build event command line" to run something custom. The idea is to make a simple console application that does what I described above. But I don't know how to get the correct file to send to said application.
Am I on the right track? How do I send the desired file to the trimming application? Is there a better way?
Edit:
This is what I had in mind when I said "simple console application".
It does everything I needed it to do (trimming white-space and adding a portion of the code to clipboard). Only thing missing is that I have to specify the file name I want it to use. Which isn't important, it would just be nice.
using System;
using System.Windows.Forms;
namespace TrimFileToClipboard
{
class Program
{
[STAThread()]
static void Main(string[] args)
{
string startString = (args.Length > 1) ? "#region " + args[1] : "#region in-game";
string line;
string trimmed = "";
bool read = false;
int depth = 0;
System.IO.StreamReader file = new System.IO.StreamReader(args[0]);
while ((line = file.ReadLine()) != null)
{
if (!read && line.Contains(startString)) read = true;
else if (read && line.Contains("#region")) depth++;
else if (read && line.Contains("#endregion"))
{
if (depth == 0) break;
else if (depth < 0)
{
Console.WriteLine("There's something wrong with your #regions. Please edit the file.");
Console.ReadLine();
Environment.Exit(0);
}
else depth--;
}
else if (read) trimmed += line.Trim() + "\n";
}
file.Close();
Clipboard.SetText(trimmed);
}
}
}
It can be used by adding
"<path>\TrimFileToClipboard.exe" "$(ProjectDir)<classname>.cs"
to Pre-build event command line, in the project properties/Build events. Where <path> is the path to the application above and <classname> is the file you want to process.
Maybe I should post this part as an answer but I don't know if it's a decent approach or an ugly hack.
Instead of coping the code to the clipboard, I save it directly inside the game as saved workshop script with this simple C# console application.
The SE script I edit using VS has the comments \\script-begin and \\script-end to tell the application where to look for the actual code that needs to be in the programmable block.
After the execution the script will be available at the local workshop. It makes it very easy to work with the SE scripts, whenever I make a change using VS, I run the console application again and the script will be updated inside the game.
internal class Program
{
private static void Main(string[] args)
{
String[] InputLines, outputLines;
Int32 scriptBegin = 0, scriptEnd = 0;
String scriptName = args[0];
String inputPath = "C:\\Users\\hfand\\source\\repos\\se-scripts\\" + scriptName + ".cs";
if (File.Exists(inputPath))
{
InputLines = File.ReadAllLines(inputPath);
for (int i = 0; i < InputLines.Length; i++)
{
if (InputLines[i].Contains("script-begin"))
{
scriptBegin = i + 1;
}
if (InputLines[i].Contains("script-end"))
{
scriptEnd = i - 1;
}
}
outputLines = new List<string>(InputLines).GetRange(scriptBegin, scriptEnd - scriptBegin + 1).ToArray();
for (int i = 0; i < outputLines.Length; i++)
{
if (outputLines[i].Length >= 8)
{
outputLines[i] = outputLines[i].Substring(8);
}
}
String outputPath = "C:\\Users\\hfand\\AppData\\Roaming\\SpaceEngineers\\IngameScripts\\local\\" + scriptName;
if (Directory.Exists(outputPath))
{
File.WriteAllLines(outputPath + "\\Script.cs", outputLines);
}
else
{
Directory.CreateDirectory(outputPath);
File.WriteAllLines(outputPath + "\\Script.cs", outputLines);
}
Console.WriteLine(scriptName + " sincronizado");
}
else
{
Console.WriteLine("Arquivo \"" + inputPath + "\" não encontrado");
}
}
}
Here is an example of how the code in VS should look like
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using VRageMath;
using VRage.Game;
using Sandbox.ModAPI.Interfaces;
using Sandbox.ModAPI.Ingame;
using Sandbox.Game.EntityComponents;
using VRage.Game.Components;
using VRage.Collections;
using VRage.Game.ObjectBuilders.Definitions;
using VRage.Game.ModAPI.Ingame;
using SpaceEngineers.Game.ModAPI.Ingame;
namespace BlankScript
{
public class Program : MyGridProgram
{
//script-begin
public Program()
{
}
public void Save()
{
}
public void Main(string argument, UpdateType updateSource)
{
}
//script-end
}
}
You can write a C# command with my Visual Commander extension that gets active file path in Visual Studio as DTE.ActiveWindow.Document.FullName and then runs your file.ReadLine() loop over it and calls Clipboard.SetText(trimmed) at the end. See for example Copy current file, line, method sample code.

Project Euler #4 in C#

I'm attempting to do Project Euler problem #4 in C#. The problem I'm having is that when the code runs a console window briefly appears and then goes away. I don't know what the problem could be as I'm relatively new to programming.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
for (int i = 1000; i > 100; i--)
for (int j = 1000; j > 100; j--)
PalCheck(i * j);
}
static void PalCheck(int original)
{
var reversed = new string(Convert.ToString(original).ToCharArray().Reverse().ToArray());
if (Convert.ToString(original) == reversed)
Console.WriteLine(original);
Console.ReadKey();
}
}
}
The code seems to be stuck at the line
Console.ReadKey() as at this line of code, the program is waiting for some input key.
Since you have not used any message before ReadKey(), you don't realize that the program is waiting for some input and not stuck.
Move Console.ReadKey() after PalCheck(i * j) and you should see the output on the console screen.

Issue trying to solve Project Euler #1

I'm having a problem trying to make a small app to solve Project Euler Problem #1.
Whenever I attempt to run this, it returns as 0, instead of 233168.
I'm not necessarily looking for an absolute answer, just some hints, I'm trying to learn.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x;
List<int> listOne = new List<int>();
for (x = 1; x < 1000; ++x)
{
if(x%3 == 0 || x%5 == 0)
{
listOne.Add(x);
}
Console.WriteLine(listOne.Sum());
Console.ReadLine();
}
}
}
}
In the interests of helping you learn, I'm not going to provide the exact answer.
Have a look at the scoping of your Console.WriteLine() statement. My guess is that it's not running when you think it should be.

Categories

Resources