I have added key in settings file as <add key="Test.Directory" value="Data/Test/XML_Files" />.I need to pass this path to File.WriteAllText and concatenate as c:/Data/Test/XML_Files/TestFile but the path is taken only till c:/Data/Test/XML_Files.Please help to concatenate and get the full path
var xmlFilePath = ConfigurationManager.AppSettings["Test.Directory"];
string _xmlFileName = new DirectoryInfo(Path.GetFullPath(xmlFilePath));
string Records = string.Empty;
using (StringWriter Writer = new Utf8StringWriter())
{
xmlSerializer.Serialize(Writer, itemList);
Records = Writer.ToString();
}
File.WriteAllText(string.Format(#_xmlFileName + "'\'TestFile" + ".dat" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + Guid.NewGuid().ToString().Substring(1, 5) ), Records);
You error seems to be in those quotes added around the backslash before the TestFile constant. But I strongly suggest you to be more clear in your building of the filename and to use Path.Combine to create the final full filename
string timestamp = DateTime.Now.ToString("yyyyMMddHHmmssfff") +
Guid.NewGuid().ToString().Substring(1, 5);
string file = Path.Combine(_xmlFileName, $"TestFile-{timestamp}.dat");
File.WriteAllText(file, Records);
Of course you could put everything in a single line, but this will not be a noticeable advantage of any kind for your performances and makes the understanding of the code really difficult. (Note, for example, that your original code has the datetime/guid part after the extension and this is probably an oversight caused by the complexity of the expression)
Maybe you can try something like this?:
var folderName = Path.Combine(#_xmlFileName, "TestFile");
var fileName = $#"{folderName}\{DateTime.Now:yyyyMMddHHmmssfff}.dat";
File.WriteAllText(fileName, txRrcWellRecords);
Related
I have a dropdown with list of file names. When a file name is selected in the dropdown I do the following
string filename = ddl.SelectedItem.Text;
string path = "F:\\WorkingCopy\\files\\" + filename +".docx";
DownloadFile(path,filename);
In the file folder files may contain any extension . Since i have hard coded ".docx" in string path everything works fine. But I need to get the extension of the file name with the ddl.SelectedItem.Text alone. Can you tell me how to do this?
Things I have
1.) File name without extension in
string filename = ddl.SelectedItem.Text;
2.) Path where the file is located
string path = "F:\\WorkingCopy\\files\\" + filename
I am trying to get the file extension with these . Can any one suggest on this?
You can use Directory.EnumerateFiles() like this:
string path = "F:\\WorkingCopy\\files\\";
string filename = ddl.SelectedItem.Text;
string existingFile = Directory.EnumerateFiles(path, filename + ".*").FirstOrDefault();
if (!string.IsNullOrEmpty(existingFile))
Console.WriteLine("Extension is: " + Path.GetExtension(existingFile));
Directory.EnumerateFiles searches the path for files like filename.*. Path.GetExtension() returns the extension of the found file.
In general, I prefer to use EnumerateFiles() instead of GetFiles because it returns an IEnumerable<string> instead string[]. This suggests that it only returns the matching files as needed instead searching all matching files at once. (This doesn't really matter in your case, just a general note).
Use the Directory.GetFiles() method. Something like this
string[] files = Directory.GetFiles("F:\\WorkingCopy\\files\\", filename+".*");
This should get you an array of filenames with the same filename but different extensions. If you have only one, then you can always use the first one.
You can use Directory.GetFiles Method:
string result = Directory.GetFiles(path, filename + ".*").FirstOrDefault();
see here
here " * " is the WildCard and will search for the Filename starts with YourFileName.
you can achieve that with followed by line
try
{
var extensions = new List<string>();
var files = Directory.GetFiles("F:\\WorkingCopy\\files\\", filename + ".*", System.IO.SearchOption.TopDirectoryOnly);
foreach (var tmpfile in files)
extensions.Add(Path.GetExtension(tmpfile));
}
catch (Exception ex)
{
throw ex;
}
will this help you?
You can simply split them by dot, For example, try this code
string folder = #"F:\\WorkingCopy\\files\\";
var files = System.IO.Directory.GetFiles(folder, filename + ".*");
if (files.Any())
{
string ext = System.IO.Path.GetExtension(files.First()).Substring(1);
}
This code gives me result that the extension for this is txt file.
I'm trying to create a path using Path.Combine() but I am getting unexpected results.
using System;
using System.IO;
namespace PathCombine_Delete
{
class Program
{
static void Main(string[] args)
{
string destination = "D:\\Directory";
string destination02 = "it";
string path = "L:\\MyFile.pdf";
string sourcefolder = "L:\\";//In other instances, it could be L:\\SomeFolder\AndMayBeAnotherFolder
string replacedDetails = path.Replace(sourcefolder + "\\", "");
string result = Path.Combine(destination, destination02, replacedDetails);
Console.WriteLine(result);
Console.ReadKey();//Keep it on screen
}
}
}
I would expect the result D:\\Directory\it\MyFile.pdf but instead, I get L:\MyFile.pdf
I can't see why? I admit it's late in the evening here, but still, I've used Path.Combine many times, and since .NET 4.0 it allows the string param to be passed. However, it appears to be ignoring the first 2 and only reading the last.
Here is the error
string replacedDetails = path.Replace(sourcefolder + "\\" , "");
You are adding another backslash and nothing is found to be replaced.
Removing the added backslash gives the correct string to search for and replace
string replacedDetails = path.Replace(sourcefolder , "");
however you could avoid all that replace stuff and intermediate variables just with
string result = Path.Combine(destination, destination02, Path.GetFileName(path));
I would recommend using:
string replacedDetails = Path.GetFileName(path);
That will handle removing the source folder from the path without using string replacement, which isn't necessarily reliable if you're getting the path from elsewhere (eventually).
Have you read the documentation? Have you verified what you're passing to Path.Combine()? The documentation says, and I quote:
path1 should be an absolute path (for example, "d:\archives" or "\archives\public").
If path2 or path3 is also an absolute path, the combine operation discards all
previously combined paths and resets to that absolute path.
That should hint at the problem.
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.
I am doing Image uploader in Asp.net and I am giving following code under my controls:
string st;
st = tt.PostedFile.FileName;
Int32 a;
a = st.LastIndexOf("\\");
string fn;
fn = st.Substring(a + 1);
string fp;
fp = Server.MapPath(" ");
fp = fp + "\\";
fp = fp + fn;
tt.PostedFile.SaveAs("fp");
But during uploading or saving image the error message comes that The SaveAs method is configured to require a rooted path, and the path 'fp' is not rooted.
So Please help me what is the problem
I suspect the problem is that you're using the string "fp" instead of the variable fp. Here's the fixed code, also made (IMO) more readable:
string filename = tt.PostedFile.FileName;
int lastSlash = filename.LastIndexOf("\\");
string trailingPath = filename.Substring(lastSlash + 1);
string fullPath = Server.MapPath(" ") + "\\" + trailingPath;
tt.PostedFile.SaveAs(fullPath);
You should also consider changing the penultimate line to:
string fullPath = Path.Combine(Server.MapPath(" "), trailingPath);
You might also want to consider what would happen if the posted file used / instead of \ in the filename... such as if it's being posted from Linux. In fact, you could change the whole of the first three lines to:
string trailingPath = Path.GetFileName(tt.PostedFile.FileName));
Combining these, we'd get:
string trailingPath = Path.GetFileName(tt.PostedFile.FileName));
string fullPath = Path.Combine(Server.MapPath(" "), trailingPath);
tt.PostedFile.SaveAs(fullPath);
Much cleaner, IMO :)
Use Server.MapPath():
fileUploader.SaveAs(Server.MapPath("~/Images/")+"file.jpg");
If you want to save the uploaded file to the value of fp, just pass it in, don't put it in quotes:
tt.PostedFile.SaveAs(fp);
When reading the title of the question, I was thinking that it looked like you had put quotation marks around the variable name. Not really believing that it was so, I opened the question to read it, but it really was so...
We cannot use the "SaveAs" method to write directly to an FTP server.
Only local paths and UNC paths are supported for the above method.
To save it to FTP, please use the FtpWebRequest class.
You will get the full details to this in the same type of question answer in social.msdn.
Please go through the link.. and you will be able to solve the issue..
enter link description here
--thanks for the answer by Jesse HouwingXPirit (MCC, Partner, MVP)
I encountered the same problem. The problem is that you did not specify the path of the server that you want the file to be saved. And here is a probably simpler answer:
string fileName = tt.PostedFile.FileName;
string savePath = Server.MapPath("Path/Of/The/Folder/Comes/Here/") + fileName);
tt.PostedFile.SaveAs(savePath);
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);