This is some code to unblock any website from listview, but now I want to unblock a website which has previously been blocked. How can I do this?
String path = #"C:\Windows\System32\drivers\etc\hosts";
StreamWriter sw = new StreamWriter(path, true);
String sitetoblock = "\n 127.0.0.1 http://"+listView1.SelectedItems[0].Text+"";
sw.Write(sitetoblock);
sw.Close();
MessageBox.Show(listView1.SelectedItems[0].Text " blocked");
It's not the right way to block a website, but here is the way to 'unblock' a site that is 'blocked' by your code is simply :
read the host file
find the site url by regex
delete the line
save the file.
You can use System.IO.File's ReadAllLines & WriteAllLines functions
and just strip out the line you want to remove
string path = #"C:\Windows\System32\drivers\etc\hosts";
string [] lineArray = System.IO.File.ReadAllLines(path);
List<string> lines = blah.ToList();
string sitetoUNblock = string.Format("127.0.0.1 http://{0}", listView1.SelectedItems[0].Text);
lines.Remove(sitetoUNblock);
System.IO.File.WriteAllLines(path, lines.ToArray());
Code Golf
string path = #"C:\Windows\System32\drivers\etc\hosts";
string itemText = listView1.SelectedItems[0].Text;
File.WriteAllLines(path, File.ReadAllLines(path).Where(site=>site!=string.Format("127.0.0.1 http://{0}", itemText)));
Just replace hosts file to original.
if you want original hosts file then i can send you.
Related
I have a template I'm using to print labels, what I'm currently doing is a Replace() on the variable parts of my template and print it as is.
What is the best way to recover the original template after printing ? Revert manually all the changes ? Not modifying the template at first but create a copy that I modify, print and delete ?
The template looks like :
data1 : $1
data2 : $2
data3 : $3
data4 : $4
and then Replace() + print with :
string text = File.ReadAllText(filePath);
text = text.Replace("$1", textBoxNumOF.Text);
text = text.Replace("$2", designation);
text = text.Replace("$3", textBoxNumOF.Text.Substring(textBoxNumOF.Text.Length - 4));
text = text.Replace("$4", "1");
File.WriteAllText(filePath, text, UTF8Encoding.UTF8);
PrintDialog pd1 = new PrintDialog();
pd1.PrinterSettings = new PrinterSettings();
EnvoiImpression.SendFileToPrinter(#"Datamax-O'Neil H-4310 (Copie 1)", filePath);
Read your template and write the output which you are sending to the printer into a temp file inside the temp directory of windows.
Please see the following function:
public static string GetTempFile()
{
// get temporary path
var tempPath = Path.GetTempPath();
// get temporary filename
string tempFileName = Path.GetRandomFileName();
//combine
return Path.Combine(tempPath, tempFileName);
}
This way you do not need to revert your template and comply with the rules for temporary files on Windows. I suggest that you remember the files for deleting all your temporary files again from disk after your program / method was successful.
The function
EnvoiImpression.SendFileToPrinter(#"Datamax-O'Neil H-4310 (Copie 1)", filePath);
is sadly unknown to my. But perhaps there is also an overload which does accept a Stream? If so, you could edit your template in a MemoryStream and do not even need to write to the disk.
Okay so I'm working with c# winforms and I have this code so far to create a ReadMe.txt and the folder itself
string folderName = #"C:\Test";
string text = "This is used Test.";
if (!System.IO.File.Exists(folderName))
{
System.IO.Directory.CreateDirectory(folderName);
File.Create(#"C:\Test\ReadMe.txt");
System.IO.File.WriteAllText(#"C:\Test\ReadMe.txt", text);
//Need to add Test.js to the folder C:\Test Here
}
As you can see above I need to add the Test.js to the folder.
Please and Thank you.
(P.S Yes it is added as a resource already)
Your code has a slight bug on line 3. It is using File.Exists instead of Directory.Exists to test if the Test Folder exists.
string folderName = #"C:\Test";
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
string readMeFileName = Path.Combine(folderName, "ReadMe.txt");
string text = "This is used Test.";
File.WriteAllText(readMeFileName , text);
string jsFileName = Path.Combine(folderName, "Test.JS");
File.Copy("Test.js", jsFileName);
File.Copy Method is what you are looking for.
i want to open a css file using C# 4.5 and change only one file at a time.
Doing it like this gives me the exception - URI formats are not supported.
What is the most effective way to do it ?
Can I find the line and replace it without reading the whole file ?
Can the line that I am looking and than start to insert text until
cursor is pointing on some char ?
public void ChangeColor()
{
string text = File.ReadAllText("http://localhost:8080/game/Css/style.css");
text = text.Replace("class='replace'", "new value");
File.WriteAllText("D://p.htm", text);
}
I believe File.ReadAllText is expecting a file path, not a URL.
No, you cannot search/replace sections of a text file without reading and re-writing the whole file. It's just a text file, not a database.
most effective way to do it is to declare any control you want to alter the css of as "runat=server" and then modify the CssClass property of it. There is no known alternative way to modify the css file directly. Any other hacks is just that.. a hack and very innefficient way to do it.
As mentioned before File.ReadAllText does not support url. Following is a working example with WebRequest:
{
Uri uri = new Uri("http://localhost:8080/game/Css/style.css");
WebRequest req = WebRequest.Create(uri);
WebResponse web = req.GetResponse();
Stream stream = web.GetResponseStream();
string content = string.Empty;
using (StreamReader sr = new StreamReader(stream))
{
content = sr.ReadToEnd();
}
content.Replace("class='replace'", "new value");
using (StreamWriter sw = new StreamWriter("D://p.htm"))
{
sw.Write(content);
sw.Flush();
}
}
I'm developing a console application that parse xml files and generate a txt file. I have created the file path to store the new file, but this is having white spaces, like this:
string filePath = "C:\\Program Files\\my path\\fileName.txt"
but I'm creating the path using:
string filePath = Path.Combine(temp, "fileName.txt");
while temp is the previous path. And when I call:
StreamWriter sw = File.CreateText(filePath);
Is giving this exception:
Could not find a part of the path: filePath
Can someone help me with this issue?? how can I create the file with this path?
there looks like a problem with you file path
try#"C:\Program Files\my path\fileName.txt"
Note: You've updated your question with the changes mentioned in the comments.
Your issue is probably that 'my path' doesn't exist as this console application works OK for me when run as an administrator. When not run I get an UnathorizedAccessException
class Program
{
static void Main(string[] args)
{
try
{
var temp = #"C:\\Program Files\\my path\\";
string filePath = Path.Combine(temp, "fileName.txt");
StreamWriter sw = File.CreateText(filePath);
Console.WriteLine("I got here");
}
catch (Exception)
{
Console.WriteLine("I didn't");
//
}
}
}
Use this:
string filePath = #"C:\Program Files\my path\fileName.txt"
You have single backslashes in the string. Make them double backslashes:
string filePath = "C:\\Program Files\\my path\\fileName.txt"
I am listing pdf files using C#, but some files wont open because they have percentage(%) signs on their filenames, the user still wants the % to be shown on the filename, but I can't get it to work.
DirectoryInfo directory = new DirectoryInfo("mydirectory/News Files");
FileSystemInfo[] files = directory.GetFiles("*.pdf");
var orderedFiles = files.OrderByDescending(f => f.Name);
foreach (FileSystemInfo file in orderedFiles)
{
var link = new HyperLink { ID = file.FullName };
link.NavigateUrl ="/News Files/"+ file.Name;
link.Text = Regex.Split(file.Name, ".pdf")[0];
link.CssClass = "linkpdf";
newsListContainer.Controls.Add(link);
}
But with this code file with the name like my20%sign.pdf will not open in the browser.
You could try Uri.EscapeUriString.
Also, you shouldn't construct urls/filenames using string concatenation with /. You should usually use a Uri/filename parsing library, such as the Uri class
That's not surprising. The %20 is interpreted by the browser as a "white space", as it is the url encoded equivalent value. So if your file is named "My%20File.pdf", the browser will decode the url and actually look for "My File.pdf".
For further reference, check this: http://www.w3schools.com/tags/ref_urlencode.asp
You can replace %20 with " ". filename.replace("%20"," ");