creating a new folder with todays date on specific folder - c#

I am trying to create a new folder with todays date on specific given path:
string LocalDirectory = Directory.CreateDirectory(
DateTime.Now.ToString("I:\\test\\final test\\snaps\\dd-MM-yyyy"));
But I receive this error:
Cannot implicitly convert type 'System.IO.DirectoryInfo' to 'string'

As per the documentation for Directory.CreateDirectory, CreateDirectory returns a DirectoryInfo object, not a string.
So do this:
DirectoryInfo localDirectory = Directory.CreateDirectory(...
or this:
var localDirectory = Directory.CreateDirectory(...
(which will basically do the same thing)

The code can be written as :
String Todaysdate = DateTime.Now.ToString("dd-MMM-yyyy");
if(!Directory.Exists("I:\\test\\final test\\snaps\\" + Todaysdate)
{
Directory.CreateDirectory("I:\\test\\final test\\snaps\\" + Todaysdate);
}

Directory.CreateDirectory return a DirectoryInfo not string
you can try something like this
DirectoryInfo LocalDirectory = Directory.CreateDirectory(string.Format("I:\\test\\final test\\snaps\\{0}-{1}-{2}", DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year));
to get the path as string
string strLocalDir = LocalDirectory.FullName;

Here is about the simplest way of creating a new folder named with todays date.
using System;
namespace CreateNewFolder
{
class Program
{
static void Main(string[] args)
{
string Todaysdate = DateTime.Now.ToString("-dd-MM-yyyy-(hh-mm-ss)");
{
Directory.CreateDirectory("c:/Top-Level Folder/Subfolder/Test" + Todaysdate);
}
}
}
}
Output of New folder name:
Test-02-05-2018-(11-05-02)
I put the hours, minutes and seconds inside some parentheses for clarity.
You can take out any part of the date to return only the time/date portion you want to call your folder. If you don’t want to call it “Test-02-05-2018-(11-05-02)” but simply have todays date as the name; like “02-05-2018”, then remove the “Test” from the “CreateDirectory” line but leave a blank space between -Subfolder/ and the closing quotation mark. Like this:
Directory.CreateDirectory("c:/Top-Level Folder/Subfolder/ " + Todaysdate);
Notice that I added a hyphen between the date parameters. This is just a visual separator for the date, you could also use a “space” as the separator.
I know this string is about 4 years old, but maybe this will help another newbie just starting out in C#.
Enjoy and share.

Take into account the culture
var rootOutputDir = #"I:\test\final test\snaps";
var Todaysdate = DateTime.Now.ToString(CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern.Replace("/", "-"));
Directory.CreateDirectory(Path.Combine(rootOutputDir, Todaysdate));

string path = Server.MapPath(#"/Content/");
path = Path.Combine(path,DateTime.Now.ToString('ddmmyyyy'));
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}

I wanted to create directories for the year and then the month inside the year folder.
Here's what worked for me:
public void CreateDirectory()
{
string strArchiveFolder = (#"\\fullpath" + DateTime.Now.Year.ToString() + "\\" +
DateTime.Now.Month.ToString());
if (!Directory.Exists(strArchiveFolder))
{
Directory.CreateDirectory(strArchiveFolder);
}

Related

How to extract date only from a file name using C#

I have a situation where I need to extract dates from the file names whose general pattern is [XXXX_BBBB]_YYYY-MM-DD[.fileExtension] example Sales_person_2019-05-03.xlsx.
I am using c# in the SSIS script task component to achieve this.
below is my code:
public void Main()
{
// TODO: Add your code here
string pat;
string date;
string filename = 'Sales_person_2019-05-03.xlsx'
// Get the Date part from the file name only
pat = #"[0-9]{2}[0-9]{2}[0-9]{4}";
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
date = r.Match(filename);
MessageBox.Show(date.ToString());}
Dts.TaskResult = (int)ScriptResults.Success;
}
but this is not working. Can someone help, please. Newbie on C#
You can achieve this without regular expressions, just use string functions (IndexOf() and Substring()):
Since you are handling fixed pattern [XXXX_BBBB]_YYYY-MM-DD[.fileExtension], just retrieve the 10 characters located after the second underscore.
public void Main()
{
string filename = "Sales_person_2019-05-03.xlsx";
// Get the Date part from the file name only
string filedate = filename.Substring(filename.IndexOf('_',filename.IndexOf('_') + 1) + 1,10);
DateTime dt = DateTime.ParseExact(filedate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None)
Dts.TaskResult = (int)ScriptResults.Success;
}

Inserting on file path

Right now I have files being output to a path; "C:\Users\Daniel\Average.txt"
I'm trying to write a function to input the current timestamp after the "Average" but before the .txt
I know this is pretty elementary, but I don't know where to begin...
EDIT: I originally had it hardcoded;
string path = "C:\Users\Daniel\Average.txt";
You can just use this instead:
var outputFile = #"C:\Users\Daniel\Average.txt";
var outputDir = Path.GetDirectoryName(outputFile);
var fileWithTimeStamp = string.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(outputFile),
DateTime.Now.ToString("yyyyMMddHHmmssffff"),
Path.GetExtension(outputFile));
var outputWithTimeStamp = Path.Combine(outputDir, fileWithTimeStamp);
My Test with LINQPad:
outputWithTimeStamp.Dump();
C:\Users\Daniel\Average_201304230828184465.txt
You can use Path.GetFileNameWithoutExtension.
var info=new FileInfo(#"C:\Users\Daniel\Average.txt");
var span=TimeSpan.FromTicks(DateTime.Now.Ticks).ToString();
var name=Path.GetFileNameWithoutExtension(info.FullName);
name=(new[] { name, span, info.Extension }).Aggregate(String.Concat);
The name is what you want finally.
There's another way to composite with a full name:
var info=new FileInfo(#"C:\Users\Daniel\Average.txt");
var span=TimeSpan.FromTicks(DateTime.Now.Ticks).ToString();
var fullName=info.FullName;
var length=fullName.LastIndexOf(info.Extension);
fullName=fullName.Substring(0, length);
fullName=(new[] { fullName, span, info.Extension }).Aggregate(String.Concat);
I think something like this will work for you:
StreamWriter sw = new StreamWriter("C:\Users\Daniel\Average"+DateTime.Now.ToString(ADD_FORMAT_HERE) +".txt");
Then you will need to dump the contents into the file.
Try string.format:
string Today = DateTime.Now.ToString("MMMM_dd");
string name = string.Format(#"Average_{0}.txt",Today);
You can alter the DateTime.Now.ToString( to include seconds, minutes etc...
//have a string variable which holds your output
String output;
File.WriteAllText("C:\Users\Daniel\Average" + DateTime.Now + ".txt",output);
this will create the text file and writes the output to that file.

How to get the second to last directory in a path string in C#

For example,
string path = #"C:\User\Desktop\Drop\images\";
I need to get only #"C:\User\Desktop\Drop\
Is there any easy way of doing this?
You can use the Path and Directory classes:
DirectoryInfo parentDir = Directory.GetParent(Path.GetDirectoryName(path));
string parent = parentDir.FullName;
Note that you would get a different result if the path doesn't end with the directory-separator char \. Then images would be understood as filename and not as directory.
You can also use a subsequent call of Path.GetDirectoryName
string parent = Path.GetDirectoryName(Path.GetDirectoryName(path));
This behaviour is documented here:
Because the returned path does not include the DirectorySeparatorChar
or AltDirectorySeparatorChar, passing the returned path back into the
GetDirectoryName method will result in the truncation of one folder
level per subsequent call on the result string. For example, passing
the path "C:\Directory\SubDirectory\test.txt" into the
GetDirectoryName method will return "C:\Directory\SubDirectory".
Passing that string, "C:\Directory\SubDirectory", into
GetDirectoryName will result in "C:\Directory".
This will return "C:\User\Desktop\Drop\" e.g. everything but the last subdir
string path = #"C:\User\Desktop\Drop\images";
string sub = path.Substring(0, path.LastIndexOf(#"\") + 1);
Another solution if you have a trailing slash:
string path = #"C:\User\Desktop\Drop\images\";
var splitedPath = path.Split('\\');
var output = String.Join(#"\", splitedPath.Take(splitedPath.Length - 2));
var parent = "";
If(path.EndsWith(System.IO.Path.DirectorySeparatorChar) || path.EndsWith(System.IO.Path.AltDirectorySeparatorChar))
{
parent = Path.GetDirectoryName(Path.GetDirectoryName(path));
parent = Directory.GetParent(Path.GetDirectoryName(path)).FullName;
}
else
parent = Path.GetDirectoryName(path);
As i commented GetDirectoryName is self collapsing it returns path without tralling slash - allowing to get next directory.Using Directory.GetParent for then clouse is also valid.
Short Answer :)
path = Directory.GetParent(Directory.GetParent(path)).ToString();
Example on the bottom of the page probably will help:
http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname(v=vs.110).aspx
using System;
namespace Programs
{
public class Program
{
public static void Main(string[] args)
{
string inputText = #"C:\User\Desktop\Drop\images\";
Console.WriteLine(inputText.Substring(0, 21));
}
}
}
Output:
C:\User\Desktop\Drop\
There is probably some simple way to do this using the File or Path classes, but you could also solve it by doing something like this (Note: not tested):
string fullPath = "C:\User\Desktop\Drop\images\";
string[] allDirs = fullPath.split(System.IO.Path.PathSeparator);
string lastDir = allDirs[(allDirs.length - 1)];
string secondToLastDir= allDirs[(allDirs.length - 2)];
// etc...

Remove part of the full directory name?

I have a list of filename with full path which I need to remove the filename and part of the file path considering a filter list I have.
Path.GetDirectoryName(file)
Does part of the job but I was wondering if there is a simple way to filter the paths using .Net 2.0 to remove part of it.
For example:
if I have the path + filename equal toC:\my documents\my folder\my other folder\filename.exe and all I need is what is above my folder\ means I need to extract only my other folder from it.
UPDATE:
The filter list is a text box with folder names separated by a , so I just have partial names on it like the above example the filter here would be my folder
Current Solution based on Rob's code:
string relativeFolder = null;
string file = #"C:\foo\bar\magic\bar.txt";
string folder = Path.GetDirectoryName(file);
string[] paths = folder.Split(Path.DirectorySeparatorChar);
string[] filterArray = iFilter.Text.Split(',');
foreach (string filter in filterArray)
{
int startAfter = Array.IndexOf(paths, filter) + 1;
if (startAfter > 0)
{
relativeFolder = string.Join(Path.DirectorySeparatorChar.ToString(), paths, startAfter, paths.Length - startAfter);
break;
}
}
How about something like this:
private static string GetRightPartOfPath(string path, string startAfterPart)
{
// use the correct seperator for the environment
var pathParts = path.Split(Path.DirectorySeparatorChar);
// this assumes a case sensitive check. If you don't want this, you may want to loop through the pathParts looking
// for your "startAfterPath" with a StringComparison.OrdinalIgnoreCase check instead
int startAfter = Array.IndexOf(pathParts, startAfterPart);
if (startAfter == -1)
{
// path not found
return null;
}
// try and work out if last part was a directory - if not, drop the last part as we don't want the filename
var lastPartWasDirectory = pathParts[pathParts.Length - 1].EndsWith(Path.DirectorySeparatorChar.ToString());
return string.Join(
Path.DirectorySeparatorChar.ToString(),
pathParts, startAfter,
pathParts.Length - startAfter - (lastPartWasDirectory?0:1));
}
This method attempts to work out if the last part is a filename and drops it if it is.
Calling it with
GetRightPartOfPath(#"C:\my documents\my folder\my other folder\filename.exe", "my folder");
returns
my folder\my other folder
Calling it with
GetRightPartOfPath(#"C:\my documents\my folder\my other folder\", "my folder");
returns the same.
you could use this method to split the path by "\" sign (or "/" in Unix environments). After this you get an array of strings back and you can pick what you need.
public static String[] SplitPath(string path)
{
String[] pathSeparators = new String[]
{
Path.DirectorySeparatorChar.ToString()
};
return path.Split(pathSeparators, StringSplitOptions.RemoveEmptyEntries);
}

Putting date in front of xml file name

I have the following code:
XmlSerializer SerializeObj = new XmlSerializer(dirs.GetType());
TextWriter WriteFileStream = new StreamWriter(#"G:\project\tester.xml");
SerializeObj.Serialize(WriteFileStream, dirs);
WriteFileStream.Close();
I'm trying to put a date/time stamp in FRONT of the xml file name. Therefore, using this example, i'd have something like 0615_Tester.xml
Any ideas on how to do this? I want to make sure i can do date/time__[filename].xml and still specify it to be on my G:\
Thanks in advance.
This is Simply achieved with System.IO.Path:
string path = "G:\\projects\\TestFile.xml";
string NewPath = System.IO.Path.GetDirectoryName(path) +
System.IO.Path.DirectorySeperatorChar +
DateTime.Now.ToString() +
System.IO.Path.GetFileName(path);
You can add a using Reference to keep the Typing down, or Format the Date in any way you want as long as its a string. Using the DirectorySeperator Variable is reccommended, although you are probably programming for Windows If using .NET (Mono?)
Use string.Format - for example:
string dateString = "0615";
string fileName = string.Format(#"G:\project\{0}_tester.xml", dateString);
... = new StreamWriter(fileName);
Building up "dateString" should be trivial from DateTime.Now.
Try something like this:
string filePath = string.Format("G:\\project\\{0}tester.xml", Date.Now.ToString("DDMM"));
TextWriter WriteFileStream = new StreamWriter(filePath);
I'm assuming that the file already exists. So you will have to copy the file and delete the old one. Like this:
File.Copy(OldFileName, NewFileNameWithDate);
File.Delete(OldFileName);
string yourDateString = DateTime.Now.ToString(); // replace with any way you want to get your date string
string filename = "G:\\project\\" + yourDateString + "_tester.xml";
TextWriter WriteFileStream = new StreamWriter(filename);

Categories