Make a new file who's name is a directory path - c#

I'm creating a csv file with a bunch of data. This file is going to be pushed up to another location and its name is going to be used to put it in the directory it belongs in. I need to create the filename to mimic a directory, without actually using that directory.
I'm using the below, basically "outputDirectory" is where the file should live, everything after it needs to be part of the filename.
String fileName = outputDirectory + DateTime.Now.ToString("yyyy-mm-hh") + "//" + app + "//" + client +"//" + site +"//" + unit + ".csv";
using (StreamWriter sw = new StreamWriter(fileName, false))
{
foreach (AFValue AFval in AFvals)
{
string tagname = AFval.PIPoint.Name;
string timestamp = AFval.Timestamp.ToString();
string value = AFval.Value.ToString();
var newLine = string.Format("{0},{1},{2}", tagname, timestamp, value);
sw.Write(newLine);
sw.Write(Environment.NewLine);
}
}
So right now this code is throwing an exception with
'Could not find a part of the path 'C:\Users\user\Desktop\Output\2019-53-01\app\client\site\Unit.csv'.'
I need it to create a file in 'C:\Users\user\Desktop\Output\' called
2019-53-01\app\client\site\Unit.csv'.'
Any ideas?

You cannot use the slash **** in the file name.
Here is an excerpt from Naming Files, Paths, and Namespaces
Use any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following:
The following reserved characters:
< (less than)
(greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
(asterisk)
Integer value zero, sometimes referred to as the ASCII NUL character.
Characters whose integer representations are in the range from 1 through 31, except for alternate data streams where these characters are allowed. For more information about file streams, see File Streams.
Any other character that the target file system does not allow.

Related

C# Adding Whitespace around a specific character for spacing in file names

I'm building a program which processes documents based on their file path and file name.
My current solution is based on file names containing 3 strings each separated by a space, dash and another space so that a valid name would be: "STRING1 - STRING2 - STRING3.pdf".
My program reads these values by using IndexOf().
string1.Substring(fileName.IndexOf("-") - 1)
string3.Substring(fileName.LastIndexOf("-") + 2)
The problem is that this breaks when the file names don't contain whitespaces, therefore breaking everything. So I opted to use Regex instead but how would I add a condition, so it doesn't add spaces to a name which already contains them.
Example,
String fileName[1] = "Test123 - Dog - Page 1.pdf"
String fileName[2] = "Test123-Dog-Page1.pdf"
Regex.Replace(fileName[1], "-", " - ");
Regex.Replace(fileNameB[2], "-", " - ");
Output:
fileName[1] = Test123 - Dog - Page 1.pdf
fileName[2] = Test123 - Dog - Page 1.pdf
fileName[1] was originally valid, now it's invalid.
fileName[2] was originally invalid, now it's valid.
I need both to be valid via an if condition.
Ps. Apologies if anything is unclear, I'm new to posting on Stack
You don't need regex, in case pure string methods are more readable for you:
string FixFileName(string fn)
{
string fnwe = System.IO.Path.GetFileNameWithoutExtension(fn);
return string.Join(" - ", fnwe.Split('-').Select(token => token.Trim()))
+ System.IO.Path.GetExtension(fn);
}
Demo: https://dotnetfiddle.net/alv6sB

File formatting with Regex

I am trying to split a string into multiple matches, each containing 'name', 'attributes' and 'files' (files only applies to a file with the directory attribute)
The string I'm trying to format: (I'm using the Hex-edit program as a test folder)
Hex Edit\ 1pÝó/Õ\<changelog.txt\ RÖ©òó/Õ ð`s7bÆÔ%ªòó/Õ < \HxD32.exe\ %ovòó/Õ ð‚fNcÆÔ­ÿ—òó/Õ< Þ \HxD64.exe\ ¤M˜òó/Õ ð‚fNcÆÔ:Ùžòó/Õ) †e" \license.txt\ “Lªòó/Õ ðõhÿªÔ“Lªòó/Õ¯? c \readme.txt\ ·&Ÿòó/Õ ðËóyÿªÔp°©òó/Õ„? ¦
\Settings\ IRýòó/Õ\<HxD Hex Editor.ini\ ÉÌ"ô/Õ ôeìÔ)3ÖôeìÔ)3Ö¸Ž? õ \HxD Hex Editor.lang\ yýòó/Õ yýòó/Õyýòó/Õ­•? ” \>>
Currently I am using (?<name>.+?)\\(?<attributes>.{10}( .{32})*?)\\(?<files>(<(?:[^<>]*|(?<open>\<)|(?<-open>\>))+(?(open)(?!))>)*)
The way the file is formatted:
filename\attributes\files
attributes can either be .{10}\s.{32} or .{10} followed by the \.
There isn't always files but if there is then files would be < + more files (recursive, can go to infinity) + >.
What I was hoping this Regex would respond with:
Name: Hex Edit
Attributes: 1pÝó/Õ
Files: <changelog.txt\ RÖ©òó/Õ ð`s7bÆÔ%ªòó/Õ < \HxD32.exe\ %ovòó/Õ ð‚fNcÆÔ­ÿ—òó/Õ< Þ \HxD64.exe\ ¤M˜òó/Õ ð‚fNcÆÔ:Ùžòó/Õ) †e" \license.txt\ “Lªòó/Õ ðõhÿªÔ“Lªòó/Õ¯? c \readme.txt\ ·&Ÿòó/Õ ðËóyÿªÔp°©òó/Õ„? ¦
\Settings\ IRýòó/Õ\<HxD Hex Editor.ini\ ÉÌ"ô/Õ ôeìÔ)3ÖôeìÔ)3Ö¸Ž? õ \HxD Hex Editor.lang\ yýòó/Õ yýòó/Õyýòó/Õ­•? ” \>>
For each match that I returned, if it had no files I would add it to a treeview otherwise I would perform the same Regex on it (until there is none left, eventually making a treeview that has all the files in it).
I have been attempting this for just over two hours now and still have not gotten any closer with my current attempt being (?<name>[^\\/:*?<>"|]+?)\\(?<attributes>.{10}( .{32})*?)\\(?<files>\<(?>\<(?<c>)|[^<>]+|\>(?<-c>))*(?(c)(?!))\>).
The Regex needs to be .net compatible.
Sorry for poor explaination, I am unsure how to word this aswell as it being my first post.
Try following :
string input = File.ReadAllText(FILENAME);
string pattern = #"^(?'name'[^\\]+)\\(?'attribute'[^\\]+)\\(?'files'.*)";
Match match = Regex.Match(input,pattern);
string name = match.Groups["name"].Value;
string attribute = match.Groups["attribute"].Value;
string files = match.Groups["files"].Value;

Extract text from large file using RegEx?

I have a big file that has a bunch of data in it, but essentially what I would like to do is to grab only parts of it, let me explain what parts I'm interested in:
(imagine "x" as an IP Address)
(imagine "?" as any alphanumerical character /w any length)
(imagine "MD5" as an MD5 hash)
(Actual -not literally though- text file below)
'xxx.xxx.xxx.xxx'
xxxxxxxxxx
'?'
'?'
'MD5'
Now my inquiry is the following one, How could I identify the line
'xxx.xxx.xxx.xxx'
anywhere at the beginning inside a file and then automatically write to another file both of the '?' entries and the 'MD5' entry for each IP Address instances found.
So in a nutshell, the program should start at the beginning of the file, read the contents, if it hits an IP Address (Regex: '\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b' works fine for me), skip one line below, then start copying the other data to another file until it hits the MD5 entry (Regex: '[a-f0-9]{32}' works fine for me), then iterate again from that point and so on looking for another instance of an IP Address etc, etc. It should keep doing that until it reaches the end of the file.
I'm trying to do this myself but I don't even know where to start, or methods of doing it at all.
You can use the following to match the content that you are looking for.. and copy it to the desired location/ file:
('\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b')(\s*.+\s*)([\s\S]*?)('\b[a-f0-9]{32}\b')
And extract $1$3$4
See DEMO
Code:
String regex = "('\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b')(\\s*.+\\s*)([\\s\\S]*?)('\\b[a-f0-9]{32}\\b')";
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(myString);
while (m.find()) {
System.out.println("end(): " + m.group(1));
//System.out.println("end(): " + m.group(2));
System.out.println("end(): " + m.group(3));
System.out.println("end(): " + m.group(4));
}
Given the fact that your file is machine generated and that the overall pattern is pretty specific, I don't think it's necessary to be overly specific with the IP address.
Matching it as "a bunch of digits and dots in single quotes" is probably enough, in the context of the rest of the pattern (*).
Here is an expression that matches your entire requirement into named groups:
^'(?<IP>[\d.]+)'\s+
^(?<ID>\w*)\s+
^'(?<line1>\w*)'\s+
^'(?<line2>\w*)'\s+
^'(?<MD5>[A-Fa-f0-9]{32})'
Use it with the Multiline and IgnorePatternWhitespace regex options (the latter means you can keep the regex layout for better readability).
(*) Besides, regex patterns for IP addresses are literally all over the place, in countless examples. Of course you can use something more sophisticated than '[\d.]+' if you think it's necessary.
I have tried out this in Java as below.
public class TestRegex
{
/**
* #param args
*/
public static void main(String[] args)
{
String input = "assasasa 123.234.223.223 333 aad sddsf 343sdd sds23343 ssdfs33344 MD5=aas jjsjjdjd 143.234.223.223 333 aad sddsf 343sdd sds23343 ssdfs33344 MD5=asas";
String regexPattern = "(\\b[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\b).*?([A-Z a-z]+[0-9]+=.*?\\s)";
Matcher m = null;
Pattern pattern = Pattern.compile(regexPattern);
m = pattern.matcher(input);
// System.out.println(matcher.toString());
while (m.find()) {
System.out.println("start(): " + m.start());
System.out.println("end(): " + m.end());
System.out.println("end(): " + m.toString());
System.out.println("end(): " + m.group(1));
System.out.println("end(): " + m.group(2));
}
}
}

C#: Save image error

i am trying to save a new image, but then C# give me an error like the following image
the error refer to the following code
string oldfilename = valid.getStringBeforeAnyChar(fi.Name, '.'); //"1"
string newfilename = FolderDir + "\\" + subfolderoutput + "\\" + oldfilename + Copyright + fi.Extension;
//"C:\\Users\\RHIT ! Solution\\Desktop\\direktori\\Output\\1[Watermarked by : RHIT Watermarker ].png"
try
{
imgPhoto.Save(newfilename, ImageFormat.Jpeg); // <-- error here
imgPhoto.Dispose();
imgWatermark.Dispose();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
where did i go wrong ? how to resolve this ? i don't know can be an output folder limit to create a new file
Windows File Paths do not support the colon (:) character, as well as several others for file names:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx#naming_conventions
In summation; invalid characters are:
< (less than)
> (greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
* (asterisk)
The backslash (\) character may appear only when used as a folder/directory delimiter.
It's almost certainly something wrong with newFileName. You can view the value of this in the debugger to see what might be amis with the intended filename & path.
As a general piece of advice though, it is better to combine directory and file name into a path using Path.Combine() which sorts out lots of potential issues like double or missing '\'.

C# getting first Characters of a file name

I have a directory name "C:\Folder\160_Name_2013111914447.7z" what I need is to extract the "160" from the file name in C# and use it to pass it to a MS-SQL method so I can move the file to a correct file Namely "160".
Please help, as I'm kinda new to C#.
Try something like this:
Path.GetFileName(#"C:\Folder\160_Name_2013111914447.7z").Split('_')[0];
Or possibly
string fileName = Path.GetFileName(#"C:\Folder\160_Name_2013111914447.7z");
Regex.Match(fileName, "^([0-9]+)_").Groups[1].Value;
If you need to take the first 3 symbols, you can use the Substring method of the string class:
string fileName = Path.GetFileName(#"C:\Folder\160_Name_2013111914447.7z");
// take 3 symbols starting from 0th character.
string extracted = fileName.Substring(0, 3);
If you can have variable length of key characters and the underscore character is the separator, then we'll have to modify the above code a little. First, we'll need the index of the underscore:
string fileName = Path.GetFileName(#"C:\Folder\160_Name_2013111914447.7z");
// get the zero-based index of the first occurrence of an underscore:
int underscoreIndex = fileName.IndexOf("_");
The string.IndexOf(...) methods returns -1 if match is not found, so we need to check for it.
if (underscoreIndex >= 0)
{
string extracted = fileName.Substring(0, underscoreIndex);
}
else
{
// no underscore found
throw new InvalidOperationException(
"Cannot extract data from file name: " + fileName);
}
To get the number assuming the file path you input will always be at the start and a length of 3 characters you can use.
FileInfo fileInfo = new FileInfo(path);
string name = fileInfo .Name;
int startingNumber = Convert.ToInt32(name.Substring(0,3));
where path is the full path of the file your using

Categories