Code Code - 5 days ago 7
C# Question

Appending file name giving back incorrect string

I'm currently trying to add a

DateTime
stamp, a prefix and a unique number to a file name. My desired output is:


\ParentDirectory\Sub Directory\Another Sub Directory\Prefix- Unique Number - 11 29 2016 2 07 30 PM.xlsx


Prefix
and
Unique Number
above will be passed into the function. I'm using the following method to achieve this:

public static string AppendDateTimeToFileName(this string fileName, string prefix, string uniqueNumber)
{
return string.Concat(
Path.GetFullPath(fileName),
Path.Combine(prefix + " - " + uniqueNumber + " - "),
Path.GetFileNameWithoutExtension(fileName),
DateTime.Now.ToString()
.Replace("/", " ")
.Replace(":", " ")
.Trim(),
Path.GetExtension(fileName)
);
}


I call the above method as:

string fileName = @"\\ParentDirectory\Sub Directory\Another Sub Directory\MyFile.xlsx";
string adjustedFileName = fileName.AppendDateTimeToFileName("Shipping Note", "0254900");


The output I receive is as follows:


\ParentDirectory\Sub Directory\Another Sub Directory\Shipping Note -\0254900 - 11 29 2016 2 08 10 PM


As you can see in the above output the string is incorrect, firstly I get an extra
-\
and the file extension isn't coming through either. Can someone tell me where I'm going wrong please.

Answer

The posted version of your code give the following output:

\ParentDirectory\Sub Directory\Another Sub Directory\MyFile.xlsxShipping Note - 0254900 - MyFile29 11 2016 15 46 48.xlsx

and NOT as you posted:

\ParentDirectory\Sub Directory\Another Sub Directory\Shipping Note -\0254900 - 11 29 2016 2 08 10 PM

if your desired output is:

\ParentDirectory\Sub Directory\Another Sub Directory\Prefix- Unique Number - 11 29 2016 2 07 30 PM.xlsx

You need to move the directory into the Path.Combine and use GetDirectoryName. Also remove the line:

Path.GetFileNameWithoutExtension(fileName)

since in your desired output I don't see the old file name "MyFile".
This code:

public static string AppendDateTimeToFileName(this string fileName, string prefix, string uniqueNumber)
{
    return string.Concat(               
        Path.Combine(Path.GetDirectoryName(fileName), prefix + " - " + uniqueNumber + " - "),
        DateTime.Now.ToString()
        .Replace(".", " ")
        .Replace(":", " ")
        .Trim(),
        Path.GetExtension(fileName)
        );
}

will yield the following output:

\ParentDirectory\Sub Directory\Another Sub Directory\Shipping Note - 0254900 - 29 11 2016 15 39 37.xlsx

Comments