I am writing an errorlog to to file in the same directory the script exists. Id like to potentially create a new folder as it writes as well as add date/time to the filenames so they 2nd doesnt save over the first.
Here is what I have so far:
File.WriteAllBytes("ErrorLog.txt")
Thanks!
You can create a valid Windows file name with DateTime in it like this:
string filename = "ErrorLogFolder" + DateTime.Now.ToString("dd-MM-yyyy_hh-mm-ss") + ".txt";
Take a look at this sample code for naming a file
using System;
using System.IO;
class Program
{
static void Main()
{
//
// Write file containing the date with BIN extension
//
string n = string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin",
DateTime.Now);
File.WriteAllText(n, "aaa");
}
}
Related
I have very simple program. Here I set the absolute path,but C# thinks that it's a relative path and try to load the file from project directory: C:\Users\Gleb Kozyukevich\source\repos\ChangeDir\ChageDir\bin\Debug\netcoreapp3.1\C:\test\test.txt
The path really exists.
What did I miss? I can't get understand
There are multiple ways you try.
Give file path like
string sourceFilePath = #"C:\test\test.txt";
Use System.IO.Path.Combine
string sourceFilePath = System.IO.Path.Combine(new []{"C:","test","test.txt"});
That is very strange. I've reproduced the code the way I think you wrote it and the result is just fine.
Here the code I wrote:
using System;
using System.IO;
namespace ReadAllLines
{
internal class Program
{
static void Main(string[] args)
{
var lines = File.ReadAllLines(#"c:\temp\test.txt");
Console.ReadKey();
}
}
}
Here's the result:
I am writing a VTSO application that should work across multiple excel document templates. I want the add in to check the document and attempt to select the one the user is using, however I cannot figure out how to grab the current filename in c# using VTSO
Try this example:
using System;
using Excel = Microsoft.Office.Interop.Excel;
namespace Foo
{
class Program
{
static void Main(string[] args)
{
var excelApplication = (Excel.Application)CustomMarshal.GetActiveObject("Excel.Application");
var currentWorkbook = excelApplication.ActiveWorkbook;
Console.WriteLine("Current active Excel Workbook: " + currentWorkbook.Name); // or FullName to get full path to opened file
Console.ReadKey();
}
}
}
CustomMarshal and GetActiveObject() explanations can be found here:
No definition found for GetActiveObject from System.Runtime.InteropServices.Marshal C#
What i want to do here was getting an string input from the user and if that string input is in the array i want to delete it from the file (all the items in the array is actual files in my computer that got scanned at the start of the program and become one array) is there a way to do that without foreach?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
using System.Threading;
string typed = null;
string loc = AppDomain.CurrentDomain.BaseDirectory;
if (!Directory.Exists(loc + #"\shortcuts"))
{
Directory.CreateDirectory(loc + #"\shortcuts");
}
string[] directory = Directory.GetFiles(loc + #"\shortcuts");
foreach (var filed in directory)
{
File.Move(filed, filed.ToLowerInvariant());
}
string[] file = Directory.GetFiles(loc + #"\shortcuts").Select(System.IO.Path.GetFileNameWithoutExtension).ToArray();
foreach (string dir in directory)
{
}
if (typed == "exit") System.Environment.Exit(0);
//other ifs here
else if (typed == "rem")
{
//Console.WriteLine("\nNot available at the moment\n");
////add this command
Console.WriteLine("\nWhich program entry do you wish to erase?\n");
typed = Console.ReadLine().ToLower();
if (file.Any(typed.Contains))
{
File.Delete(file.Contains(typed)); //this is the broken part and i don't know how i can get the stings from there
Console.WriteLine("hi");
}
else Console.WriteLine("\n" + typed + " is not in your registered programs list.\n");
}
Expected result was getting rid of the typed program in the folder and actual results was just an error code.
You are storing only the file name in the array, not its complete path or extension. You need to change this, and allow it to store FileName with extension.
string[] file = Directory.GetFiles(loc + #"\shortcuts").Select(System.IO.Path.GetFileName).ToArray();
and then, you need to change the If condition as follows.
if (file.Contains(typed))
{
File.Delete(Path.Combine(loc + #"\shortcuts",typed));
Console.WriteLine("hi");
}
In this Scenario, user would need to input the file name with extension.
If you want the User to input only the filename(without extension, as in your code), then, you could run into a situation where there could be two files with different extension.
"test.jpg"
"test.bmp"
Update
Based on your comment that you cannot store extensions, please find the updated code below. In this scenario, you do not need to change the array. Since you are only storing lnk files, you can append the extension to the file name to complete the path during Path.Combine.
if (file.Contains(typed))
{
File.Delete(Path.Combine(loc , #"shortcuts",$"{typed}.lnk"));
Console.WriteLine("hi");
}
I have a Test.cs file in C:\ This test file reads from an input file and writes the same to an output file.
Test.cs
public class Test
{
public static int Main(string[] args)
{
var reader = new StreamReader("in.txt");
string input = reader.ReadLine();
var writer = new StreamWriter("out.txt");
writer.WriteLine(input);
return 0;
}
}
Here it should be noted that the code only uses the filename and not the full file path, which means the file is expected to be in the directory where the program is running. And I have created the in.txt in C:\
Now, there is a c# code called Runner.cs in a solution in C:\Project\Runner.cs, that dynamically compiles the Test.cs code and runs it using reflection. Now, when the Test.cs runs, it expects the in.txt file to be in C:\Project\bin\Debug\in.txt , but it is actually present in C:\in.txt
So, my question is, is there a way to make the code to get the file from C:\in.txt and not from the bin directory without changing the path of the file in the Test.cs code file.
Edit: It is my bad that I forgot to mention why I am in need of this requirement.
The Test.cs file comes from over the wire. And I felt it will not be a good choice to edit this file and set the file path accordingly. I want to compile it and run it as it is.
I hope I am clear. If not, please feel free to ask for more information.
If it is as simple as you show in your code switching the CurrentDirectory works for this example:
var mainMembers = new CSharpCodeProvider()
.CreateCompiler()
.CompileAssemblyFromSource(
new CompilerParameters { GenerateInMemory = true }
, #"
using System;
using System.IO;
public class M {
public static int Main() {
Console.WriteLine(""CurDir = ""+ Environment.CurrentDirectory);
var reader = new StreamReader(""in.txt"");
string input = reader.ReadLine();
var writer = new StreamWriter(""out.txt"");
writer.WriteLine(input);
return 0;
}
}")
.CompiledAssembly
.GetType("M")
.GetMember("Main");
// inspect
Environment.CurrentDirectory.Dump("current");
// keep
var oldcd = Environment.CurrentDirectory;
// switch
Environment.CurrentDirectory = "c:\\temp";
// invoke external code
((MethodInfo) mainMembers[0]).Invoke(null,null);
// restore
Environment.CurrentDirectory = oldcd;
In a multi threaded scenario this becomes unreliable.
My hook post-commit template calls my postcommitlog.exe to create a MyFile_LOG.txt and write to it the 3 arguments. The repository and the transaction is passed from the postcommit template.
The problem is that, after committing a file in TurtoiseSVN, there is no log created. It looks like either I do not have the permission to create a file on the repository or there is an error in my code.
My code works locally, when I Debug it and pass random arguments to it, a log file is created on my local machine. But its not working on the SVN hook.
THE TEMPLATE
\\myserver\e$\Repositories\CONRAD\hooks\postcommitlog.exe %1 %2
MY PROGRAM
using System;
using System.IO;
namespace postcommitlog
{
internal class Program
{
private static void Main(string[] args)
{
string repositories = args[0];
string transaction = args[1];
const string LOG_PATH = #"\\myserver\e$\Repositories\CONRAD\hooks\MyFile_LOG.txt";
FileInfo fileInfo = new FileInfo(LOG_PATH);
File.AppendAllText(LOG_PATH, "Repositories " + args[0]
+ "\t Transaction " + args[1] + "\t Date " + DateTime.Now.ToString("MMM ddd d HH:mm yyyy") + Environment.NewLine);
}
}
}
The mistake was that I was supposed to create a BAT file from the template, not use the template. The template does nothing, it is what it is : a template. The BAT file is run by SVN then runs the script.
More info here:
http://svnbook.red-bean.com/en/1.5/svn.reposadmin.create.html#svn.reposadmin.create.hooks