Writing to a text file with a variable for the name - c#

Alright, so my question is; I'm trying to save a file to the C: drive in a folder. Now, I know how to do this for regular files like
using(StreamWriter writer = new SteamWriter("c:\\Folder\\TextFile.txt");
What I've been trying to figure out is how I can make it so that the name of text file is the replaced with a variable so Its more like
using(StreamWriter writer = new SteamWriter("c:\\Folder\\Variablegoeshere.txt");
Is there anyway I can do this?
I apologize for my poor question asking skills.

The StreamWriter constructor, like many other constructors and method calls, takes a string argument. You can pass it any string you like. In your first code sample, you're passing the constructor a "string literal" - an unnamed string variable with a constant value. Instead, you can pass a standard string variable, that you construct beforehand. For instance:
string name = // whatever you like
string path = "c:\\Folder\\" + name + ".txt"; // use '+' to combine strings
using (StreamWriter writer = new SteamWriter(path));
I usually like to use the Path.Combine static method when I concatenate path components. Helps me avoid problems with missing or doubled backslashes:
string path = System.IO.Path.Combine("c:\\Folder", name + ".txt");
And, finally, with the string verbatim modifier, you avoid those ugly double-backslashes, that are otherwise necessary because the backslash is the "escape" character in non-verbatim strings:
string path = System.IO.Path.Combine(#"c:\Folder", name + ".txt");
Here's the Microsoft developer reference page for strings in C#. Worth a read, as is the larger C# language reference.

var inputPath = "c:\\Folder\\TextFile.txt";
var folderPath = Path.GetDirectoryName( inputPath );
using ( var writer = new StreamWriter ( Path.Combine( folderPath, "Variablegoeshere.txt" ) )

Related

C# cut file Name from Path

I am creating an Image Extraction tool and I am able to retrieve the Images with full path..
For Example:
I need to cut the File name (rss) from path...
I search posts and Tried following
//1.
//string str = s.Split('/', '.')[1];
//2.
string s1;
// string fileName = "abc.123.txt";
int fileExtPos = s.LastIndexOf(".");
if (fileExtPos >= 0)
s1 = s.Substring(0, fileExtPos);
//3.
//var filenames = String.Join(
// ", ",
// Directory.GetFiles(#"c:\", "*.txt")
// .Select(filename =>
//4.
// Path.GetFileNameWithoutExtension(filename)));
None seems to be working
I want the name between "images" and "png" ..What can be the exact code?
Any Suggestion will be helpful
Just use the class Path and its method GetFileNameWithoutExtension
string file = Path.GetFileNameWithoutExtension(s);
Warning: In this context (just the filename without extension and no arguments passed after the URL) the method works well, however this is not the case if you use other methods of the class like GetDirectoryName. In that context the slashes are reversed into Windows-style backslashes "\" and this could be an error for other parts of your program
Another solution, probably more WEB oriented is through the class Uri
Uri u = new Uri(s);
string file = u.Segments.Last().Split('.')[0];
but I find this a lot less intuitive and more error prone.
In your example you're using a uri so you should use System.Uri
System.Uri uri = new System.Uri(s);
string path = uri.AbsolutePath;
string pathWithoutFilename = System.IO.Path.GetDirectoryName(path);
Why use Uri? Because it will handle things like
http://foo.com/bar/file.png#notthis.png
http://foo.com/bar/file.png?key=notthis.png
http://foo.com/bar/file.png#moo/notthis.png
http://foo.com/bar/file.png?key=moo/notthis.png
http://foo.com/bar/file%2epng
Etc.
Here's a fiddle
You should use the various System.IO.Path functions to manipulate paths as they work cross platform. Similarly you should use the System.Uri class to manipulate Uris as it will handle all the various kinds of edge cases like escaped characters, fragments, query strings, etc.

How can I replace the same name of a file using regex but in another format?

I am new in programming and not so good about regex. I wish to load / read a csv File and then save in a txt File using the same name of csv File. I will give an example.
D:\Project\File\xxx.csv
After I load this file, I want to get the name "xxx" and save it in a txt file:
D:\Project\File\xxx.txt
Or maybe in another folder, for example:
D:\Project\Specifications\PersonInfo.csv
save to
D:\Project\DataBank\PersonInfo.txt
This can be accomplished in many ways.
Maybe what you're lacking is knowledge of the System.IO.Path class (MSDN article here).
For instance changing the extension could be accomplished like so:
string originalFilePath = #"D:\Project\File\xxx.csv";
string newFilePath = Path.ChangeExtension(originalFilePath, ".txt");
Note: You need to explicitate the leading dot (".") for the extension.
Here's some "Path algebra" fun you could combine to create your desired effects:
string originalFilePath = #"D:\Project\File\xxx.csv";
string thePath = Path.GetDirectoryName(originalFilePath);
// will be #"D:\Project\File"
string filename = Path.GetFileName(originalFilePath);
// will be "xxx.csv"
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(originalFilePath);
// will be "xxx"
string recombinedFilePath = Path.Combine( #"D:\OtherFolder", "somethingElse.txt" );
// will be #"D:\OtherFolder\somethingElse.txt"
Note: Path.Combine knows how to handle extra/missing leading/trailing backslashes.
For example:
Path.Combine(#"D:\MyFolder1", #"MyFolder2\MyFile.txt")
Path.Combine(#"D:\MyFolder1\", #"MyFolder2\MyFile.txt")
Path.Combine(#"D:\MyFolder1", #"\MyFolder2\MyFile.txt")
Path.Combine(#"D:\MyFolder1\", #"\MyFolder2\MyFile.txt")
will all yield the same result: #"D:\MyFolder1\MyFolder2\MyFile.txt"
You do not need regex for that, because .NET provides a System.IO.Path class for dealing specifically with file name manipulations.
For example, to replace .csv with .txt you can use this call:
var csvPath = #"D:\Project\File\xxx.csv";
var txtPath = Path.Combine(
Path.GetDirectoryName(csvPath)
, Path.GetFileNameWithoutExtension(csvPath)+".txt"
);
You use a similar trick to replace other parts of the file path. Here is how you change the name of the top directory:
var csvPath = #"D:\Project\Specifications\xxx.csv";
var txtPath = Path.Combine(
Path.GetDirectoryName(Path.GetDirectoryName(csvPath))
, "DataBank"
, Path.GetFileNameWithoutExtension(csvPath)+".txt"
);
You don't need Regex.
You can use Path.GetFileName or Path.GetFileNameWithoutExtension:
string fileName = Path.GetFileNameWithoutExtension("D:\Project\Specifications\PersonInfo.csv");
If you want to use regex for this, this regex will get the part you want:
([^\\]+)\.[^.\\]+$
The first group (in the parentheses) matches one or more characters (as many as possible) which is not a backslash. Then there need to be a literal dot. Then one or more characters (as many as possible) that are not a dot or backslash, then the end of the string. The group captures the wanted part.

trim a string in c#

I'm taking pdf file names in telerik sitefinity like this :
test..pdf (41 KB )
1..pdf (34 KB )
How to change these like this? test.pdf and 1.pdf
If they all look like this (two periods instead of one you could simply do:
myFileName = myFileName.Replace("..", ".");
Also it seems I didn't consider the size of the file that is appended to the path. That can be removed by splitting on the space, and taking the first element like this:
myFileName = myFileName.Split(' ')[0];
To obtain both the replacement of .. with . and remove the filesize, you can just chain them both together like this:
myFileName = myFileName.Replace("..", ".").Split(' ')[0];
If the extension is un-known, so in your case it's PDF, this simply can be done by:
string fileName = string.Format("{0}.pdf","test..pdf (41 KB )".Split('.')[0]);
if you need more flexibility, can make PDF as string variable too.
Do not simply replace, as the file can contain points too.
The String.Replace method would allow you to replace ".." with "." as long as you know there are no other cases where you may want ".."
EG:
pdfFile = pdfFile.Replace("..", ".");
simpler: string fileName = tempFileName.Replace("..pdf",".pdf");
For performance, use StringBuilder.Replace() method,
StringBuilder strBuilder = new StringBuilder(tempFileName);
strBuilder.Replace("..pdf", ".pdf");
string fileName = strBuilder.ToString();
And if you're like me who only would want one instance replaced(this is slightly tricky)
string ReverseString(string p)
{
char[] arr = p.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
var regex = new RegEx("fdp..");
var fileName = ReverseString(regex.Replace(ReverseString(tempFileName), "fdp.",1));

Does System.IO.File.Move not support previously-defined strings?

For example, something like this fails:
string oldfile = (#"C:\oldfile.txt");
string newfile = (#"C:\newfolder\newfile.txt");
System.IO.File.Move(oldfile, newfile);
Program crashes with "The given path's format is not supported."
EDIT: I'm doing this in a Windows Forms project vs. Console project, does that make a difference? Intuitively I wouldn't think it should, but you never know...
The problem is the mixture of the verbatim string format ( #"..." ) and escaping slashes ( "\" )
The second piece of code
string oldFile = #"C:\\oldfile.txt"
creates a path of 'C:\\oldfile.txt' which is not recognised as a valid path.
Either use the first version you gave
string oldFile = #"C:\oldfile.txt"
or
string oldFile = "C:\\oldfile.txt"
string oldfile = (#"C:\oldfile.txt");
string newfile = (#"C:\newfolder\newfile.txt");
System.IO.File.Move(oldfile , newfile );
or
string oldfile = ("C:\oldfile.txt");
string newfile = (#"C:\newfolder\newfile.txt");
System.IO.File.Move(oldfile , newfile );
if the direcotry not exist, create it with Directory.CreateDirectory
In a string literal prefixed with # the escape sequences starting with \ are disabled. This is convenient for filepaths since \ is the path separator and you don't want it to start an escape sequence.
You simply have to use the below one:
string oldfile = ("C:\\oldfile.txt");
string newfile = ("C:\\newfolder\\newfile.txt");
System.IO.File.Move(oldfile, newfile);
OR
string oldfile = (#"C:\oldfile.txt");
string newfile = (#"C:\newfolder\newfile.txt");
System.IO.File.Move(oldfile, newfile);
It works without crash.
Refer this MSDN Article
MSDN says to use like this
string path = #"C:\oldfile.txt";
string path2 = #"C:\newfolder\newfile.txt";
if (!File.Exists(path))
{
// This statement ensures that the file is created,
// but the handle is not kept.
using (FileStream fs = File.Create(path)) {}
}

"The given path's format is not supported."

I have the following code in my web service:
string str_uploadpath = Server.MapPath("/UploadBucket/Raw/");
FileStream objfilestream = new FileStream(str_uploadpath +
fileName, FileMode.Create, FileAccess.ReadWrite);
Can someone help me resolve the issue with this error message from line 2 of the code.
The given path's format is not supported.
Permission on the folder is set to full access to everyone and it is the actual path to the folder.
The breakpoint gave me the value of str_uploadpath as C:\\webprojects\\webservices\\UploadBucket\\Raw\\.
What is wrong with this string?
Rather than using str_uploadpath + fileName, try using System.IO.Path.Combine instead:
Path.Combine(str_uploadpath, fileName);
which returns a string.
I see that the originator found out that the error occurred when trying to save the filename with an entire path. Actually it's enough to have a ":" in the file name to get this error. If there might be ":" in your file name (for instance if you have a date stamp in your file name) make sure you replace these with something else. I.e:
string fullFileName = fileName.Split('.')[0] + "(" + DateTime.Now.ToString().Replace(':', '-') + ")." + fileName.Split('.')[1];
For me the problem was an invisible to human eye "‪" Left-To-Right Embedding character.
It stuck at the beginning of the string (just before the 'D'), after I copy-pasted the path, from the windows file properties security tab.
var yourJson = System.IO.File.ReadAllText(#"D:\test\json.txt"); // Works
var yourJson = System.IO.File.ReadAllText(#"‪D:\test\json.txt"); // Error
So those, identical at first glance, two lines are actually different.
If you are trying to save a file to the file system. Path.Combine is not bullet proof as it won't help you if the file name contains invalid characters. Here is an extension method that strips out invalid characters from file names:
public static string ToSafeFileName(this string s)
{
return s
.Replace("\\", "")
.Replace("/", "")
.Replace("\"", "")
.Replace("*", "")
.Replace(":", "")
.Replace("?", "")
.Replace("<", "")
.Replace(">", "")
.Replace("|", "");
}
And the usage can be:
Path.Combine(str_uploadpath, fileName.ToSafeFileName());
Among other things that can cause this error:
You cannot have certain characters in the full PathFile string.
For example, these characters will crash the StreamWriter function:
"/"
":"
there may be other special characters that crash it too.
I found this happens when you try, for example, to put a DateTime stamp into a filename:
AppPath = Path.GetDirectoryName(giFileNames(0))
' AppPath is a valid path from system. (This was easy in VB6, just AppPath = App.Path & "\")
' AppPath must have "\" char at the end...
DateTime = DateAndTime.Now.ToString ' fails StreamWriter... has ":" characters
FileOut = "Data_Summary_" & DateTime & ".dat"
NewFileOutS = Path.Combine(AppPath, FileOut)
Using sw As StreamWriter = New StreamWriter(NewFileOutS , True) ' true to append
sw.WriteLine(NewFileOutS)
sw.Dispose()
End Using
One way to prevent this trouble is to replace problem characters in NewFileOutS with benign ones:
' clean the File output file string NewFileOutS so StreamWriter will work
NewFileOutS = NewFileOutS.Replace("/","-") ' replace / with -
NewFileOutS = NewFileOutS.Replace(":","-") ' replace : with -
' after cleaning the FileNamePath string NewFileOutS, StreamWriter will not throw an (Unhandled) exception.
Hope this saves someone some headaches...!
If you get this error in PowerShell, it's most likely because you're using Resolve-Path to resolve a remote path, e.g.
Resolve-Path \\server\share\path
In this case, Resolve-Path returns an object that, when converted to a string, doesn't return a valid path. It returns PowerShell's internal path:
> [string](Resolve-Path \\server\share\path)
Microsoft.PowerShell.Core\FileSystem::\\server\share\path
The solution is to use the ProviderPath property on the object returned by Resolve-Path:
> Resolve-Path \\server\share\path | Select-Object -ExpandProperty PRoviderPath
\\server\share\path
> (Resolve-Path \\server\share\path).ProviderPath
\\server\share\path
Try changing:
Server.MapPath("/UploadBucket/Raw/")
to
Server.MapPath(#"\UploadBucket\Raw\")
This was my problem, which may help someone else -- although it wasn't the OP's issue:
DirectoryInfo diTemp = new DirectoryInfo(strSomePath);
FileStream fsTemp = new FileStream(diTemp.ToString());
I determined the problem by outputting my path to a log file, and finding it not formatting correctly. Correct for me was quite simply:
DirectoryInfo diTemp = new DirectoryInfo(strSomePath);
FileStream fsTemp = new FileStream(diTemp.FullName.ToString());
Does using the Path.Combine method help? It's a safer way for joining file paths together. It could be that it's having problems joining the paths together
I had the same issue today.
The file I was trying to load into my code was open for editing in Excel.
After closing Excel, the code began to work!
I am using the (limited) Expression builder for a Variable for use in a simple File System Task to make an archive of a file in SSIS.
This is my quick and dirty hack to remove the colons to stop the error:
#[User::LocalFile] + "-" + REPLACE((DT_STR, 30, 1252) GETDATE(), ":", "-") + ".xml"
Image img = Image.FromFile(System.IO.Path.GetFullPath("C:\\ File Address"));
you need getfullpath by pointed class. I had same error and fixed...
If the value is a file url like file://C:/whatever, use the Uri class to translate to a regular filename:
var localPath = (new Uri(urlStylePath)).AbsolutePath
In general, using the provided API is best practice.

Categories

Resources