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 '\'.
Related
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
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.
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));
}
}
}
I have problem in opening file with ambersand in between.
var attachment = "attachment;" + "&test& incident&.txt";
HtmlPage.Window.CreateInstance("foo2", new object[] { Id.ToString(), attachment });
function foo2(theAlert, type) {
alert(type);
window.open('fileViewer.aspx?Id=' + theAlert + '&Type=' + type);
}
When i try to get the type in another page i am getting only the "attachment;" because it taking the words before ampersand. and missing my filename. If i give file name without ampersand i dont have any problem in opening the file.
Any one help me please?
Thanks in advance.
You can use encodeURIComponent
The encodeURIComponent() function encodes a URI component.
This function encodes special characters. In addition, it encodes the
following characters: , / ? : # & = + $ #
window.open('fileViewer.aspx?Id=' + theAlert + '&Type=' + encodeURIComponent(type));
Try the following:
window.open("fileViewer.aspx?Id=" + theAlert + "&Type=" + encodeURIComponent(type));
Changed from encodeURI to encodeURIComponent:
encodeURI is intended for use on the full URI.
encodeURIComponent is intended to be used on .. well .. URI components that is any part that lies between separators (; / ? : # & = + $ , #).
Path.GetFullPath(path); works fine. But Directory.CreateDirectory(path); throws a path too long exception. Can it be that the backslashes are counted differently for the two methods?
In ILSpy it seems that GetFullPath uses the private const MaxDirectoryLength(255) whereas CreateDirectory uses 248.
Path.GetFullPath -> GetFullPathInternal -> NormalizePath
// System.IO.Path
private static readonly int MaxDirectoryLength = 255;
// ...
if (num8 - num5 > Path.MaxDirectoryLength)
{
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
}
// ...
Directory.CreateDirectory -> InternalCreateDirectory (btw, NormalizePath is also called before InternalCreateDirectory)
// ...
string text2 = list[list.Count - 1];
list.RemoveAt(list.Count - 1);
if (text2.Length >= 248)
{
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
}
// ...
So it seems that a folder name cannot be longer than 248 chars whereas the full path (incl. each subfolder) can be longer.
Escape characters "are counted" at compile time, so both methods see a single character (backslash) not two. Escape characters are "invisible" once the application is compiled, they are only visible in the source code; in other words, "\\" sequence is resolved at compile time (not runtime) and converted to a single backslash.
You must be reaching Windows Max Path size (248 chars) , so the
Directory.CreateDirectory(path);
Can not create the directory.
Can you paste the Directory path?