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.
}
Related
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 3 years ago.
Improve this question
I am working on an application developed in C # .net WPF, I wanted to know how to make every launch of my application,
Detect if there is an "Affaires" directory in "%AppData%\Roaming\N.O.E" and, if not, create the directory.
Detect if there is an "Affaires" directory in "C:\N.O.E" and, if there is, prompt the user if they want to move the directory to AppData. If yes, move the directory.
The installation is done with an administrator account.
Should the detection code for my application be in the class "App.XAML.cs"?
Code of the method that launches the application is:
protected override void OnStartup(StartupEventArgs e)
{
Application.Current.DispatcherUnhandledException +=
new
try
{
// Créé le répertoire des traces s'il n'existe pas déjà
string cwd = Directory.GetCurrentDirectory();
string logPath = Path.Combine(cwd, "log");
if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(logPath);
}
// Log4Net configuration
FileInfo log4NetConfig = new FileInfo(Path.Combine(cwd,
"Log4net.config"));
log4net.Config.XmlConfigurator.Configure(log4NetConfig);
// Récupère la version de l'application
System.Reflection.Assembly assembly =
System.Reflection.Assembly.GetExecutingAssembly();
Version version = assembly.GetName().Version;
UpdateService.CheckingForUpdates();
Log.Info("Démarrage de l'application " +
OtherHelper.GetAppSetting("NomApplication", "N.O.E") + "
version " + version);
ConfigService.InitializeConfigPathAndModificationDate();
TagService.InitializeReferential();
}
catch (Exception ex)
{
////////
}
base.OnStartup(e);
}
Depending which AppData folder you need, you can retrieve the folder you need using Environment.GetFolderPath().
So, to check for directory "Affaires" in AppData\Roaming\N.O.E create it if it doesn't exist, for example:
string appDataLocalPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string affairesDirPath = appDataRoamingPath + "\\N.O.E.\\Affaires";
if(!Directory.Exists(affairesDirPath))
{
DirectoryInfo affairesDir = Directory.CreateDirectory(affairesDirPath);
//Do anything else you need to with the directory here.
}
If you only need to create the directory without doing anything else with it, then you can simple use Directory.CreateDirectory(affairesDirPath);; it will not create the directory if it already exists.
For your other directory, you can do the following:
string affairesDirPath = "C:\\N.O.E.\\Affaires";
if(Directory.Exists(affairesDirPath))
{
//Move the directory
}
I have a requirement where my scheduler will run twice in a day. One in the morning and a second time in evening. When I run my current code it stores the file in a folder.
So again when I run the same application in the evening what happens is that the same file which is saved earlier in the morning is getting updated again which I don't want to happen. I want to save both the files. So what should I do?
Below is my current code. Please give me suggestions
public void ExportExcel(string strWorkbookName, DataSet ds)
{
string strDateFolder = "";
string strFileName = ConfigurationManager.AppSettings["FileName"].ToString();
try
{
using (XLWorkbook wb = new XLWorkbook())
{
strDateFolder = DateTime.Now.ToString("dd-MM-yyyy");
if (Directory.Exists(strDateFolder))
{
Directory.CreateDirectory(strDateFolder);
}
wb.Worksheets.Add(ds);
wb.SaveAs(ConfigurationRead.GetAppSetting("ReportDirectory") + "\\" + strDateFolder + "\\" + strFileName);
}
}
catch (Exception)
{
throw;
}
}
UPDATE
Also, I want to delete the folder created after 7 days..Is that also possible ?
strDateFolder will contain the same value through both runs because it gets the date. You may want to add time to that so it creates another file. Like this:
strDateFolder = DateTime.Now.ToString("dd-MM-yyyy-hh");
Then, the code below is like saying: if this directory exists, create it.
if (Directory.Exists(strDateFolder))
{
Directory.CreateDirectory(strDateFolder);
}
You can use only this, because it will create it only if it does not exist:
Directory.CreateDirectory(strDateFolder);
Update from post:
This would delete your folders older that 6 days
CultureInfo enUS = new CultureInfo("en-US");
string path = ConfigurationRead.GetAppSetting("ReportDirectory");
DateTime currentDate = DateTime.Now.AddDays(-7);
foreach (string s in Directory.GetDirectories(path))
{
string folderPath = s.Remove(0, path.Length);
if (DateTime.TryParseExact(folderPath, "dd-MM-yyyy hhmmss", enUS, DateTimeStyles.AssumeLocal, out DateTime td))
{
if (td <= currentDate)
{
Directory.Delete(s, true);
}
}
}
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.
namespace SimpleLicense
{
class Program
{
static void Main(string[] args)
{
string fileName = #"C:\\Temp\\test.txt";
try
{
// Check if file already exists. If yes, delete it.
if (File.Exists(fileName))
{
File.Delete(fileName);
}
// 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(31);
sw.WriteLine("License Expires After"+" "+newDate);
sw.WriteLine("Number of Days Remaining ");
sw.Close();
// sw.WriteLine("Add ");
// sw.WriteLine("Done! ");
}
// 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());
}
}
}
}
Contents of .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
Hi Everyone,
I have written the above code to store date and time information to a .txt file as given above.I want that the information about the remaining days be stored in .txt file.As you can see today's date is 20-5-2014 and the license expires on 20-6-2014.So 30 should be printed next to Number Of Days Remaining.
If the user changes the system clock,and changes the date to say 21-5-2014, then 29Days should be printed next to Number of Days remaining
I also want that when the application is executed on a particular date, the date should be set to that date ie at installed date and should not change and the remaining days be calculated on the basis of Installed date
Can anyone help me to figure this out?
Thanks
This code will give you the number of days:
int numberOfDays = newDate.Subtract(DateTime.Now).Days;
sw.WriteLine("Number of Days Remaining: " + numberOfDays.ToString());
you can used below menioned code
var Remainingdays=(LicenseExpires-InstalledDate).TotalDays
and if you want in int days then
var Remainingdays=(LicenseExpires-InstalledDate).Days
I assume you want to do time limited version of software?
While code posted in previous answers is technically correct, you probably shouldn't use DateTime.Now as user can tamper with system clock and circumvent your measure. Get current date from another source, like:
http://www.worldtimeserver.com/
This has its disadvantages though, like increased startup time and what if a page or user's connection is down?
Better and easier solution would be to forget about time limitation and limit amount of times application can be started instead. Then you simply load number on opening program and write decreased one on closing.
Also, storing relevant values as plaintext (with helpful user-friendly descriptions no less!) is probably not a good idea as any halfway savvy user may just snoop through files and edit them in any text editor. You may want to use some kind of encryption algorithm like AES:
http://msdn.microsoft.com/pl-pl/library/system.security.cryptography.aes%28v=vs.110%29.aspx
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.