File.Move issue: Process cannot access the file exception - c#

I am getting an error when I run this newFile method:
class logFile
{
public static string logpath = #"D:\Program Files\CustomApps\DataFeed\";
public static void log(string log)
{
string timestamp = DateTime.Now.ToString("yyyy_MM_ddTHH_mm_ss");
Console.WriteLine(timestamp + log);
File.AppendAllText(logpath + #"log_file_current.txt", timestamp + log + Environment.NewLine);
}
public static void newFile()
{
if (File.Exists(logpath + #"log_file_current.txt") == true)
{
File.Move(logpath + #"log_file_current.txt"
, logpath + #"log_files\log_file_ORPHANED_" + DateTime.Now.ToString("yyyy_MM_ddTHH_mm_ss") + ".txt");
}
try
{
File.Create(logpath + #"log_file_current.txt");
logFile.log("logFile created.");
}
catch(System.NotSupportedException ex)
{
Console.WriteLine(ex.Message);
}
}
}
I get the following error:
If I comment the body of the "newFile" code out then it runs without error, but then I would need to manually archive. If I comment out the File.Move part it all runs fine so this is the culprit.
How can I release the file so that it can be moved?

You need to use File.Close after using File.Create, this is why you are getting an error saying the file is used by another process. Try adding this line to your code :
try
{
File.Create(logpath + #"log_file_current.txt").Close(); // Notice the .Close() here
logFile.log("logFile created.");
}
Source : Closing a file after File.Create

Try this one
public static void log(string log)
{
string timestamp = DateTime.Now.ToString("yyyy_MM_ddTHH_mm_ss") + ": ";
Console.WriteLine(timestamp + log);
using (StreamWriter sw = File.AppendText(logpath + #"log_file_current.txt"))
{
sw.WriteLine(timestamp + log);
}
}

Related

New line in a string is not works with text file

I have a function to write a message to text file. But when passing a string with 'Environment.NewLine', it is not writes a new line to the text file. Instead it writes '\r\n'.
How to correct this? I have tried with '\n' instead of 'Environment.NewLine'. Still the new line is not coming.
The issue is happens only when passing a string with new line to the function. Like variable 'message'
string message= "First "+Environment.NewLine+" message.";
LogTheDetails(message);
public static void LogTheDetails(String message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\logs";
var directory = new DirectoryInfo(path);
if (directory.Exists == false)
{
directory.Create();
}
string FilePath = path + "/" + currentdate + ".txt";
if (!File.Exists(FilePath)) //FILE WRITING FIRST TIME
{
File.Create(FilePath).Dispose();
using (TextWriter tw = new StreamWriter(FilePath))
{
tw.WriteLine("============================================================\n --Logs--");
}
}
else if (File.Exists(FilePath))//IF FILE ALREADY EXIST - APPEND LINES
{
string testString= "testString"+ Environment.NewLine+ "WithNewLine";
File.AppendAllText(FilePath, "\n============================================================\n");
File.AppendAllText(FilePath, message);
File.AppendAllText(FilePath, testString);
File.AppendAllText(FilePath, "\n============================================================\n");
}
}
Output
============================================================
--Logs--
============================================================
First \r\n message.
testString
WithNewLine
============================================================
Expected Output:
============================================================
--Logs--
============================================================
First
message.
testString
WithNewLine
============================================================
Below piece of code gave the output you are looking for, I tried it in .net 5 console application.
using System;
using System.IO;
namespace ConsoleApp4
{
class Program
{
static string message = "First " + Environment.NewLine + " message.";
static void Main(string[] args)
{
LogTheDetails(message);
Console.WriteLine("Hello World!");
}
public static void LogTheDetails(string message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\logs";
var directory = new DirectoryInfo(path);
if (directory.Exists == false)
{
directory.Create();
}
string currentdate = "test";
string FilePath = path + "/" + currentdate + ".txt";
if (!File.Exists(FilePath)) //FILE WRITING FIRST TIME
{
File.Create(FilePath).Dispose();
using (TextWriter tw = new StreamWriter(FilePath))
{
tw.WriteLine("========================================================\n
--Logs--");
}
}
else if (File.Exists(FilePath))//IF FILE ALREADY EXIST - APPEND
LINES
{
string testString = Environment.NewLine + "testString" +
Environment.NewLine + "WithNewLine";
File.AppendAllText(FilePath,
"\n============================================================\n");
File.AppendAllText(FilePath, message);
File.AppendAllText(FilePath, testString);
File.AppendAllText(FilePath,
"\n============================================================\n");
}
}
}
}

Writing to outputfile within thread execution

I have following code, but if I use Console.ReadKey() then the output is written to file once I close the console, but I have to press key to exit the app. If I comment the Console.Readkey() the code exit, but output file is blank, how can I write to output file and exit the application without any manual key press ?
static void Main(string[] args)
{
try
{
int i = 1;
string[] lines = System.IO.File.ReadAllLines(#"C:\Software\ThreadTest1\ServerList.txt");
/*
ServerList.txt has file windows server names in it
*/
foreach (string linevalue in lines)
{
var value = i;
var runningTask = Task.Factory.StartNew(() => fillServiceAccountDetailsinGrid(linevalue.ToString(), value));
i = i + 1;
}
// Console.ReadKey(); // if I uncomment this list, only then the output file has message written, but then console
}
catch (Exception ex)
{
string path = #"C:\Software\ThreadTest1\Output_ServerList_Log2.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Error occurred on : " + DateTime.Now.ToString() + " : Error occurred in module 'writetoDatabase' Description : " + ex.Message.ToString());
}
}
else
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("Error occurred on : " + DateTime.Now.ToString() + " : Error occurred in module 'writetoDatabase' Description : " + ex.Message.ToString());
}
}
}
}
private static void fillServiceAccountDetailsinGrid(string srvName, int i)
{
try
{
string path = #"C:\Software\ThreadTest1\" + srvName.ToString() + ".txt";
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Error occurred on : " + DateTime.Now.ToString() + " : Error occurred in module 'writetoDatabase' Description : " + srvName.ToString());
}
}
else
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("Error occurred on : " + DateTime.Now.ToString() + " : Error occurred in module 'writetoDatabase' Description : " + srvName.ToString());
}
}
Thread.Sleep(50);
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
You are firing off Tasks asynchronously and not waiting for them to complete.
If you want synchronous concurrency try replacing your foreach loop with the following...
Parallel.For(0, lines.Length, (int lineId) =>
{
fillServiceAccountDetailsinGrid(lines[lineId].ToString(), lineId);
});
...this will not return until all actions have completed.
#Creyke is correct this is issue with task management .
List<Task> tasklist = new List<Task>();
foreach (string linevalue in lines)
{
var value = i;
tasklist.Add(Task.Factory.StartNew(() => fillServiceAccountDetailsinGrid(linevalue.ToString(), value)));
i = i + 1;
}
Task.WaitAll(tasklist.ToArray());
wating for all task will fix this.

Console.WriteLine is blank

I have a strange problem. I wrote a .net 2.0 console application running on Windows Server 2008 R2 that processes a file that's passed in via args When I run it by hand and pass in a file, I don't get an output. Nothing. No errors or exception of any kind. Event log is clear. I would expect that I get some output from the exe. I also have a Console.WriteLine in my catch statement. But again, no output whatsoever. Any ideas why?
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.IO;
namespace RTDXCentralFileTransmit
{
class Program
{
static void Main(string[] args)
{
try
{
if (args.Length < 1)
{
Console.WriteLine("File name is required");
logit("File name is required");
return;
}
string filename = args[0];
Console.WriteLine("Now doing " + filename);
logit("Now doing " + filename);
if (!File.Exists(filename))
{
Console.WriteLine("File " + filename + " does not exists. Exiting.");
logit("File " + filename + " does not exists. Exiting.");
File.WriteAllText("Error.txt", "File " + filename + " does not exists. Exiting.");
return;
}
string fileplain = File.ReadAllText(filename);
string file64 = EncodeTo64(fileplain);
if (string.IsNullOrEmpty(file64))
{
Console.WriteLine("File " + filename + " is empty. Exiting");
logit("File " + filename + " is empty. Exiting");
File.WriteAllText("Error.txt", "File " + filename + " is empty. Exiting");
return;
}
FileInfo fi = new FileInfo(filename);
com.xxxxxxxxxxxxxxxxxx.api.Dispatch dis = new com.xxxxxxxxxxxxxxxx.api.Dispatch();
com.xxxxxxxxxxxx.api.FunnelResult fr = dis.Funnel(file64, fi.Name);
if (fr.Success)
{
Console.WriteLine("Success! " + fr.Result);
logit("Success! Response from the server: " + fr.Result);
File.WriteAllText("Success.txt", fr.Result);
return;
} else
{
Console.WriteLine("Failed!! " + fr.Result);
logit("Failed!! " + fr.Result);
File.WriteAllText("Error.txt", "Transmission Failed! " + fr.Result);
}
logit("Exiting for " + filename);
Environment.Exit(0);
} catch (Exception e)
{
Console.WriteLine("Error. " + e.ToString());
return;
}
}
static void logit (string s)
{
File.AppendAllText("FileTransmit.log",DateTime.Now.ToString() + ":" + s + Environment.NewLine);
}
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes
= System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
}
}
I found it. The issue was between the chair and the computer.
The project that I cloned, even though it had tons of Console.WriteLine, it was actually was being built as Windows Application. That explains why we have no output for the Console.WriteLine.
Since it was being build as windows application, the console doesn't wait for the program to finish. It returns right away - which totally threw me off seeing that many console.writelines. However, the program is still running and, with a large file, it takes a while to post it to the remote server. After waiting a minute or two all of 10 MB file was transmitted successfully as it was indicated in the logs.

UNITY C# Screenshot issue

I'm trying to write some code to take screenshot and save them in android default DCIM path, first part for take screenshot works but second part for move file to Path not work.
public class IS_Screenshot : MonoBehaviour
{
string ScreenShotFile;
void Start ()
{
ScreenShotFile = Application.persistentDataPath + "_Screenshot_" + System.DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss") + ".png";
Debug.Log (ScreenShotFile);
}
public void Screen_Shot()
{
try
{
Application.CaptureScreenshot(ScreenShotFile);
string Path = "/mnt/sdcard/DCIM/" + "_Screenshot_" + System.DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss_") + ".png";
Debug.Log (Path);
if(System.IO.File.Exists(ScreenShotFile))
{
System.IO.File.Move(ScreenShotFile, Path);
Debug.Log ("Screenshot file saved.");
}
else
{
Debug.Log ("Screenshot file not found.");
}
}
catch(Exception ex)
{
Debug.Log ("Screenshot capture failed. | " + ex);
}
}
}
Use Path.Combine to attach the filename to the persistentDataPath. It may well be that on Android the value of persistentDataPath does not end in a path seperator, which will result in an invalid path.
ScreenShotFile = Path.Combine(Application.persistentDataPath, "_Screenshot_" + System.DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss") + ".png");

Log file is not being created by class library after installing the dll

I have created a class library with some functionality and maintaining a log file to track the steps executed. If i run this class library in debug mode it is successfully creating log file.
But, I have created the cab file after creating the tlb file of that class library and installed into the system. Now i am using that library, all the functions are working properly, only logs files are not written.
I've used the code to create log file is below-
public static void LogTrace(string LogMessage)
{
try
{
string LogError = string.Empty;
String DirPath = string.Empty;
DirPath= Convert.ToString(ConfigurationSettings.AppSettings["DirPath"]);
LogError = Convert.ToString(ConfigurationSettings.AppSettings["LogError"]);
//if logging is not required
if (LogError.ToLower() == "true")
{
if (DirPath == null || DirPath == string.Empty)
DirPath = #"C:\LogAndError";
if (LogError == null || LogError == string.Empty)
LogError = "True";
//creation of date wise file name
string LogFileName = DirPath + "\\Log_ " + DateTime.Now.ToString("MM_dd_yyyy") + ".txt";
createLogAndErrorFile(DirPath);
StreamWriter streamWriter = null;
streamWriter = new StreamWriter(LogFileName, true);
streamWriter.WriteLine("Time :" + DateTime.Now.ToString() + " ");
streamWriter.WriteLine(LogMessage);
streamWriter.WriteLine(Environment.NewLine);
streamWriter.Flush();
streamWriter.Close();
}
}
catch
{
//We are not throwing any exception because all the exeption is logged using this method
//and throwing the exception could lead to recursive call of function.
}
}
public static void createLogAndErrorFile(string DirPath)
{
if (!Directory.Exists(DirPath))
Directory.CreateDirectory(DirPath);
}
}
Am i missing something ?
Verify that you have permission to acces to your file
Place your code in try catch block and capture exception
I suggest you to use using block
try
{
var path = Path.Combine(DirPath, string.Concat("\\Log_",DateTime.Now.ToString("MM_dd_yyyy"), ".txt"));
using (StreamWriter streamWriter = new StreamWriter(path))
{
streamWriter.WriteLine("Time :" + DateTime.Now.ToString() + " ");
streamWriter.WriteLine(LogMessage);
streamWriter.WriteLine(Environment.NewLine);
}
}
catch(Exception ex)
{
Console.Write(ex.Message);
throw ex;
}

Categories