C# program to check if file exists /time out and run [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I need to create a C# program which will check if input.txt exists (within a time-out of 5 mins), if within 5 mins the input.txt is created it will copy contents to output.txt. Then it has to delete the input.txt (and keep iterating for 10000 runs).
I am doing this to avoid a license re-launch within the program which takes quite sometime compared to program execution.
I tried with timers, Filewatcher but got totally lost.
Can someone help?

Using your flow chart for reference and it alone I managed to come up with this piece of code:
string inputPath = "<input.txt file path>";
string outputPath = "<output.txt file path>";
for (int iterator = 0; iterator < 10000; iterator++)
{
bool exists = false;
long startTimeMillis = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
while (!exists)
{
if (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond - startTimeMillis >= 5 * 60 * 1000) Environment.Exit(0);
if (File.Exists(inputPath))
{
exists = true;
FileStream f = File.Open(inputPath, FileMode.Open);
String output = String.Empty;
for (int i = 0; i < f.Length; i++)
{
output += (char)f.ReadByte();
}
f.Dispose();
File.WriteAllText(outputPath, output);
File.Delete(inputPath);
}
}
}
Environment.Exit(0);
I can't guarantee that my code is 100% applicable for your purposes but it shouldn't be too hard to implement. If need be you can run this code from within a Thread.

Related

File.Exists always returns false [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
My app is a 32 bit .Net VS 2017 app. File.Exists always returns false in my app. Either running in VS, deployed locally, or as admin. Running on a Windows 10 64 bit system. Paths are good because the File.Copy works (but always since File.Exist isn't working. I don't want File.Copy to run unless file doesn't exist. Maybe suggestions for a workaround if I can't get it to work? File permissions shouldn't be a problem since the file is in the Documents folder. Maybe a better SpecialFolder to use than MyDocuments? Any help would be appreciated. Thanks in advance. Code below.
// Class variables
public static string appPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
"\\Lottery Analyzer Expert International";
public static string dbPath = appPath + "\\database\\";
public static string dbFile = "Histories.sqlite";
// Class method
public void copyInputFiles_db()
{
string dest = dbPath + dbFile;
string src = Application.StartupPath + "\\database\\" + dbFile;
if (!File.Exists(dest)) { }
{
File.Copy(src, dest, true); // if input files not found in appPath copy from install folder
bool do_download = true;
DialogResult dialogResult2 = MessageBox.Show(
"The history database was copied from the application's startup to it's working dirctory. This happens when first running " +
"the application or the history file is missing. Would you like to update that file from the web?",
"Download file?", MessageBoxButtons.YesNo);
if (dialogResult2 == DialogResult.Yes)
{
do_download = true;
}
else if (dialogResult2 == DialogResult.No)
{
do_download = false;
}
if (do_download)
downloadAllTheHistoryFIles_db();
}
printTextFiles();
}
You know that the code below the if is always executed?
if (!File.Exists(dest)) { } // << the { } is the IF scope
{ // <- this is a new scope also, but not part of the if..
File.Copy(src, dest, true);
bool do_download = true;
// *SNIP*
}
Remove the { } behind the if

How to write to a text file from windows forms application [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am generating permutations from algorithm and writing same to a text file.,after generating it gives no error but only one permutations is found in the text file.is it encoding problem or something else i am missing.
'''
private void button2_Click(object sender, EventArgs e)
{
string str33 = textBox1.Text;
char[] arr = str33.ToCharArray();
int r = Convert.ToInt32(textBox3.Text);
int n = arr.Length;
printCombination(arr, n, r);
}
'''
The line which finally writes to the text file goes like this.
'''
File.WriteAllText(finalocation, str);
'''
where finalocation is the path of the text file and str is the string to be written to it.Anything more required i will reply further.
Store your all permutations in a list and send the list to your designed method to write in file.
The method for writing should be similar to the following.
public void printToFile(List<string> allPermutations) {
using (StreamWriter sw = new StreamWriter("names.txt")){
foreach (string s in allPermutations){
sw.WriteLine(s);
}
}
}

Task.Factory.StartNew not executing the method in .net [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have around 5000 files located in FTP, so i am downloading those by using FTP and then unzipping the files, finally processing and pushing in to oracle database.Except processing and pushing in to database everything going fine, i dont know why processing is not happeneing .I can see debugger hitting that method but it is not going in to inside method.How to fix this issue?
var list = ftp.GetFileList(remotepath);
//-------------------
DateTime dt = DateTime.Now;
string st = String.Format("{0:yyyyMMdd}", dt);//20161120
Task[] myTasks = new Task[list.Count];
int i = 0;
foreach (string item in list)
{
{
if (item.StartsWith("GExport_") && (!item.ToUpper().Contains("DUM")) && (item.Contains(st)) && (!item.ToUpper().Contains("BLK")))
{
4gpath = item;
//Downloadfile()
ftp.Get(dtr["REMOTE_FILE_PATH"].ToString() + 4gpath , #localDestnDir + "\\" + dtr["SOURCE_PATH"].ToString());
download_location_hw = dtr["LOCAL_FILE_PATH"].ToString();
// Spin off a background task to process the file we just downloaded
myTasks[i++] = Task.Factory.StartNew(() =>
{
//Extractfile()
ExtractZipfiles(download_location_hw + "//" + huwawei4gpath, dtr["REMOTE_FILE_PATH"].ToString(),
dtr["FTP_SERVER"].ToString(), dtr["FTP_USER_ID"].ToString(),
dtr["TECH_CODE"].ToString(), dtr["VENDOR_CODE"].ToString());
//Extract the zip file referred to by download_location_hw
// Process the extracted zip file
ProcessFile()
});
}
}
}
Task.WaitAll(myTasks);
Here ProcessFile() method is not executing at all
EDIT
there was typo in filepath cause issue,thanks,but my question is is there any synchronization issue,since first unzip the file and same time process file where file was not available,will it wait for unzipping before processing –
added check while(!File.Exists("")) { Thread.Sleep(1000);
does that make any isssues??
If you try this code here, you will notice it works. It is very similar to your code. Since this works, your issue is elsewhere and not related to Task(s).
class Program {
static void Main(string[] args) {
var list = new List<string> { "1", "2" };
Task[] myTasks = new Task[ list.Count ];
int i = 0;
foreach( string item in list ) {
// Spin off a background task to process the file we just downloaded
myTasks[ i++ ] = Task.Factory.StartNew( () =>
{
//Extract the zip file referred to by download_location_hw
// Process the extracted zip file
ProcessFile();
} );
}
Task.WaitAll( myTasks );
Console.WriteLine( "in main after processing..." );
Console.Read();
}
private static void ProcessFile() {
Console.Write( "Processed..." );
}
}

Store Date to a .txt file only once using c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have written code that stores the date to a .txt file as shown. I am able to store the current date and time. I want that the date should be set only once when the application is executed for the first time.
Installed Date: Set to the date when the application is executed the first time and should not change irrespective of how many time the application is executed
I am trying to implement 30Days licensing. I want that when the application is executed for the very first time, the date when he executed the application should be stored into the .txt file and should not change, so that the remaining days could be calculated on the basis of that. My main aim is to stop the user from using my application after 30 days
class Program
{
static void Main(string[] args)
{
string fileName = #"C:\\Temp\\test.txt";
try
{
// Create a new file
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
using (StreamWriter sw = File.CreateText(fileName))
{
sw.WriteLine("Thermo Licensing System file");
sw.WriteLine("------------------------------------");
sw.WriteLine("Installed Date: {0}", DateTime.Now.ToString());
DateTime newDate = DateTime.Now.AddDays(30);
DateTime date = DateTime.Now;
sw.WriteLine("License Expires After"+" "+newDate);
int numberOfDays = newDate.Subtract(date).Days;
sw.WriteLine("Number of Days Remaining: " + " " + numberOfDays.ToString());
sw.Close();
}
// Write file contents on console.
using (StreamReader sr = File.OpenText(fileName))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.ToString());
}
}
}
Output (.txt file)
Thermo Licensing System file
------------------------------------
Installed Date: 20-05-2014 16:01:42
License Expires After 20-06-2014 16:01:42
Number Of Days Remaining
You're already checking to see if the file exists, so there's no need for a variable.
if (File.Exists(fileName)) {
// Test to make sure the contents of the file are something you
// created, and not another file with the same name.
}
else {
// Continue on with your logic to create the file and add the dates.
}

The process cannot access the file because it is being used by another process error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
here is my code:
public static bool createFile(string dir) {
dir="c:\\e.bat";
System.IO.File.Create(dir);
if (System.IO.File.Exists(dir))
{
try
{
StreamWriter SW;
SW = System.IO.File.CreateText(dir);
SW.WriteLine("something ");
SW.Close();
}
catch (Exception e)
{
Console.Write(e.Message);
Console.ReadLine();
return false;
}
}
return true;
}
here dir is the current directory. i am facing the error The process cannot access the file because it is being used by another process.how can i solve this problem?
You're calling File.Create at the start of the method - which is returning you a stream, which stays open. It's not clear why you're calling that at all, but I'd suggest just removing that line.
You should also use a using statement, only catch specific exceptions, use appropriate using directives, and follow .NET naming conventions. For example:
using System.IO;
...
public static bool CreateFile(string file)
{
using (var writer = File.CreateText(file))
{
try
{
writer.WriteLine("something ");
}
catch (IOException e)
{
// TODO: Change the handling of this. It's weird at the moment
Console.Write(e.Message);
Console.ReadLine();
return false;
}
}
return true;
}
I've removed the check for the file existing, as with the previous code it would always exist because you'd just created it.
You should also consider using File.WriteAllText as a simpler way of writing the file.

Categories

Resources