i want open file xml and find string then replace.
but when replace string Only to find two strings and replace
this my code
var realpath = "~/template/xml/xmlback";
var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/template/xml/xmltest") + ".xml");
var filePath2 = Path.Combine(HttpContext.Current.Server.MapPath("~/template/xml/xmlback/test2") + ".xml");
DirectoryInfo dir = new DirectoryInfo(Path.Combine(HttpContext.Current.Server.MapPath(realpath)));
foreach (FileInfo files in dir.GetFiles())
{
files.Delete();
}
string strVal = System.IO.File.ReadAllText(Server.MapPath("~/template/xml/xmltest") + ".xml");
strVal = strVal.Replace("Test1", "amir");
strVal = strVal.Replace("Test2", "amir1");
strVal = strVal.Replace("Test3", "amir2");
strVal = strVal.Replace("Test4", "amir3");
strVal = strVal.Replace("Test5", "amir4");
strVal = strVal.Replace("Test6", "amir5");
File.Copy(Path.Combine(filePath), Path.Combine(filePath2));
System.IO.File.WriteAllText(Server.MapPath("~/template/xml/xmlback/test2") + ".xml", strVal);
ProcessRequest(filePath2, Lcourseid.Text);
im try open xml with word and see resultpic
I've solved my issue
iam use this code But no difference with the above code does not
I think it was a corrupted file xml,
Could not find Test3 and Test4,...
Thank you all
Dictionary<string, string> wordsToReplace = new Dictionary<string, string>();
wordsToReplace.Add("Test1", "amir");
wordsToReplace.Add("Test2", "amir1");
wordsToReplace.Add("Test3", "amir3");
wordsToReplace.Add("Test4", "amir4");
wordsToReplace.Add("Test5", "amir5");
wordsToReplace.Add("Test6", "amir6");
string strVal = System.IO.File.ReadAllText(Server.MapPath("~/template/xml/xmltest") + ".xml");
foreach (var pair in wordsToReplace)
{
//Performs each replacement
strVal = strVal.Replace(pair.Key, pair.Value);
}
File.Copy(Path.Combine(filePath), Path.Combine(filePath2));
System.IO.File.WriteAllText(Server.MapPath("~/template/xml/xmlback/test2") + ".xml", strVal);
ProcessRequest(filePath2, Lcourseid.Text);
Related
Inside a foreach loop, i am counting and getting the full path of files with similar names, and I need to access them later so I want to make a list that saves them, and my question is how can I do this?
I´ve been trying to do it like this.
protected void ShowPng(string pathPgnImg)
{
btnNextPage.Visible = true;
string sImageName = "";
string sImagePathImages = Server.MapPath("Anexos/");
string pngFile = "";
List<string> pngs = new List<string> { pngFile };
string FileWithoutPath = Path.GetFileName(pathPgnImg);
string fileWithoutPathAndExt = Path.GetFileNameWithoutExtension(FileWithoutPath);
if(fileWithoutPathAndExt + "_pag" + LblHiddenImagePageNumber != fileWithoutPathAndExt + "_pag" + "" )
{
DirectoryInfo AnexoDirectory = new DirectoryInfo(PathForPdf);
FileInfo[] filesInDir = AnexoDirectory.GetFiles(fileWithoutPathAndExt + "_pag" + "*.png");
foreach (FileInfo foundFile in filesInDir)
{
pngFile = foundFile.FullName;
pngs = new List<string> { pngFile };
}
string sFileExt = Path.GetExtension(pngFile);
pngFile = Path.GetFileNameWithoutExtension(pngFile);
m_sImageNameUserUpload = pngFile + sFileExt;
m_sImageNameGenerated = Path.Combine(sImagePathImages, m_sImageNameUserUpload);
//Literal1.Text += "<img src=" + '"' + pngFile + '"' + "/>";
imgCrop.ImageUrl = "Anexos\\" + Path.GetFileName(pngFile);
if (m_sImageNameUserUpload != "")
{
pnlCrop.Visible = true;
imgCrop.ImageUrl = "Anexos/" + m_sImageNameUserUpload;
Session["ImageName"] = m_sImageNameUserUpload;
}
}
}
You can find what I mean in these lines here:
foreach (FileInfo foundFile in filesInDir)
{
pngFile = foundFile.FullName;
pngs = new List<string> { pngFile };
}
So what can I do? the output right now for it is although it adds the value it doesn't save it and add the other ones just adds that one to the list.
Thank you #Knoop for the answer to this simple question.
Turns out the only problem i was having was i wasn´t adding up to the list count.
So start by making a list:
List<string> Files = new List<string>;
Since i was trying to add the value of a variable that kept updating trough a foreach loop, ill use that example:
foreach (FileInfo foundFile in filesInDir)
{
pngFile = foundFile.FullName;
pngs.Add(pngFile);
}
Just to explain what i changed from the original question post to this answer was this line:
pngs.Add(pngFile);
with the name of the list and the .ADD it keeps adding the pngFile value everytime the loop restarts.
Once again thank you to #Knoop for the help.
I hope this helps some of you too.
i need to find and delete all lines wich contain the word "recto",
i did search in stackoverflow forum, but all what i found is do that (delete the line) using path (Directory & FileName).
in my case i want to delete the line contain "recto" in all fils with specific extention (*.txt) in the directory.
thanks for help
here is my code so far
string sourceDir = #"C:\SRCE\";
string destinDir = #"C:\DIST\";
string[] files = Directory.GetFiles(sourceDir);
foreach (string file in files)
{
using (StreamReader sr_ = new StreamReader
(sourceDir + Path.GetFileName(file)))
{
string line = sr_.ReadLine();
if (line.Contains("recto"))
{
File.Copy(file, destinDir + Path.GetFileName(file));
string holdName = sourceDir + Path.GetFileName(file);
}
sr_.DiscardBufferedData();
sr_.Close();
}
}
}
You can try something like this. You were only identifying the files with the word but not making any try to remove it. At the end, you were copying the files that included the word "recto"
string sourceDir = #"C:\SRCE\";
string destinDir = #"C:\DIST\";
string[] files = Directory.GetFiles(sourceDir);
foreach (string file in files)
{
using (StreamReader sr_ = new StreamReader
(sourceDir + Path.GetFileName(file)))
{
string res = string.Empty;
while(!sr_.EndOfStream)
{
var l = sr_.ReadLine();
if (l.Contains("recto"))
{
continue;
}
res += l + Environment.NewLine;
}
var streamWriter = File.CreateText(destinDir + Path.GetFileName(file));
streamWriter.Write(res);
streamWriter.Flush();
streamWriter.Close();
}
}
If the files are not really big you can simplify a lot your code reading all lines in memory, processing the lines with Linq and then rewriting the files
string sourceDir = #"C:\SRCE\";
string destinDir = #"C:\DIST\";
string[] files = Directory.GetFiles(sourceDir);
foreach (string file in files)
{
var lines = File.ReadLines(file);
var result = lines.Where(x => x != "recto").ToArray();
File.WriteAllLines(Path.Combine(destinDir, Path.GetFileName(file)), result);
}
I'm starting to learn c # and Windows form. I create an application that transforms a resx (XML) file into an Excel.
All my code works, my Excel file is created and I can convert it to a resx file.
But, when I open my Excel file, spaces before and after my data has been added like this : Excel cell example. And when I convert it to resx file, it does
Resx file example
Here is my resx => excel code :
//I use a application WindowsForm so any 'LBL' / 'TXT make reference to label or textBox I use them to set file or folder path
private void writeExcel()
{
Dictionary<string, string> dataSave = new Dictionary<string, string>();
var path = LBL_DocumentPath.Text;
XDocument doc = XDocument.Load(path);
IEnumerable<XNode> nodes = doc.Descendants("data");
foreach (XElement node in nodes)
{
string name = node.Attribute("name").Value;
string value = node.Value;
dataSave.Add(name, value);
}
CreateExcel(dataSave);
}
private void CreateExcel(Dictionary<string, string> dico)
{
int i = 1;
FileInfo newFile = new FileInfo(LBL_FolderPath.Text + "/" + TXT_FileName.Text + ".xlsx");
using (ExcelPackage package = new ExcelPackage(newFile))
{
try
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Inventry");
worksheet.Cells[1, 1].Value = "Name";
worksheet.Cells[1, 2].Value = "value";
worksheet.Cells[1, 3].Value = "translation";
foreach (KeyValuePair<string, string> data in dico)
{
string testMessage = String.Format("{0}", data.Value);
string delSpace = testMessage;
Regex regex = new Regex(#"(\s){2,}");
testMessage = regex.Replace(delSpace, "&");
i++;
worksheet.Cells[i, 1].Value = String.Format("{0}", data.Key);
worksheet.Cells[i, 2].Value = String.Format("{0}", testMessage);
worksheet.Cells.AutoFitColumns();
}
package.Save();
MessageBox.Show("File created ! " + LBL_FolderPath.Text + "\\" + TXT_FileName.Text);
}
catch (Exception)
{
MessageBox.Show("File already exist, checks : " + LBL_DocumentPath.Text + "\\" + TXT_FileName.Text);
}
}
}
If you want all my code, I can give you a dropbox link.
Thanks in advance for any help you can give me.
Math.
Ps: My apologies, my English is not very good. I hope you will understand me correctly
Ok a friend give me solution.
It's my regex which does not work so I replace
string testMessage = String.Format("{0}", data.Value);
string delSpace = testMessage;
Regex regex = new Regex(#"(\s){2,}");
testMessage = regex.Replace(delSpace, "&");
by
string testMessage = String.Format("{0}", data.Value);
testMessage = testMessage.Replace("\n",string.Empty);
testMessage = testMessage.Replace("\r", string.Empty);
testMessage = testMessage.Replace(" ", string.Empty);
I'm trying to create a utility that will create a xml sitemap using c#. I'm able to point it at a local folder and produce results that display in a browser, but am having trouble when I point it at a website. Any tips or hints would be appreciated! I'm rather new to c#.
static void Main(string[] args)
{
//String sDir = #"WWW.WEBSITE.COM";<---I'd like to index a site rather than a file.
String sDir = #"FOLDER_LOCATION";
String siteMap = #"FOLDER_LOCATION\sitemapworking.xml";//Where I'd like to save the sitemap
var sb = new System.Text.StringBuilder();
String[] allfiles = System.IO.Directory.GetFiles(sDir, "*", System.IO.SearchOption.AllDirectories);
String[] alldirects = System.IO.Directory.GetDirectories(sDir, "*", System.IO.SearchOption.AllDirectories);
sb.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset>");
sb.AppendLine("<url>\n\t<loc>" + sDir + "</loc>\n</url>");
foreach (string s in alldirects)
{
sb.AppendLine("<url>\n\t<loc>" + s + "</loc>\n</url>");
}
foreach (string s in allfiles)
{
System.IO.FileInfo file = new System.IO.FileInfo(s);
sb.AppendLine("<url>\n\t<loc>" + s + "</loc>\n\t<lastmod> " + file.LastWriteTime + "</lastmod>\n</url>");
}
sb.AppendLine("</urlset>");
File.WriteAllText(siteMap, sb.ToString());
}
I have an XML file which have multiple messages in one large file, my objective it to split the file into singe xml file for each message, I have a c# code which only gets me the first instance of the message. can you please tell what am I missing here:
Here is my code :
string strSeq;
string strFileName;
XDocument doc = XDocument.Load(#"C:\XMl\MR.xml");
var newDocs = doc.Descendants("Message")
.Select(d => new XDocument(new XElement("FileDump", d)));
foreach (var newDoc in newDocs)
{
strSeq = XDocument.Load(#"C:\XMl\MR.xml").XPathSelectElement
"//FileDump/Message/MsgID").Value;
strFileName = "MR_" + strSeq + ".xml";
newDoc.Save(Console.Out); Console.WriteLine();
newDoc.Save(#"C:\xml\MR\Tst\" + strFileName);
Console.WriteLine();
}
You should search for message ID within newDoc instead of doc:
foreach (var newDoc in newDocs)
{
strSeq = newDoc.XPathSelectElement("//FileDump/Message/MsgID").Value;
strFileName = "MR_" + strSeq + ".xml";
newDoc.Save(Console.Out); Console.WriteLine();
newDoc.Save(#"C:\xml\MR\Tst\" + strFileName);
Console.WriteLine();
}
Try,
string path = #"C:\xml\MR\Tst\MR_";
XElement root = XElement.Load(file);
foreach(XElement message in root.Descendants("Message"))
{
string id = message.Element("MsgID").Value;
message.Save(path + id + ".xml");
}