I'm trying to load code from an exe file then create it into a new .exe file. But it's not recognizing my variable "SourceCode". It says the name "SourceCode" does not exist in the current context
private void button1_Click(object sender, EventArgs e)
{
using (FileStream SourceCode = new FileStream("thecode.exe", FileMode.Open, FileAccess.ReadWrite, FileShare.None));
string Output = textBox3.Text;
String[] Assembly = { "System.dll", "System.Drawing.dll", "System.Windows.Forms.dll" };
CodeDomProvider CodeCompiler = CodeDomProvider.CreateProvider("CSharp");
CompilerParameters Parameters = new CompilerParameters(Assembly, "");
Parameters.OutputAssembly = Output;
Parameters.GenerateExecutable = true;
Parameters.GenerateInMemory = false;
Parameters.WarningLevel = 3;
Parameters.TreatWarningsAsErrors = true;
Parameters.CompilerOptions = "/optimize+ /target:winexe";
string Errors = null;
try
{
CompilerResults Results = null;
Results = CodeCompiler.CompileAssemblyFromSource(Parameters, SourceCode); //This here is giving me an error
if (Results.Errors.Count > 0)
{
Errors = "";
foreach (System.CodeDom.Compiler.CompilerError CompileError in Results.Errors)
{
Errors += "Line number " + CompileError.Line + ", Error Number: " + CompileError.ErrorNumber + ", '" + CompileError.ErrorText + ";\r\n\r\n";
}
The following line is ending with a semicolon ';'
using (FileStream SourceCode = new FileStream("thecode.exe", FileMode.Open, FileAccess.ReadWrite, FileShare.None));
In C# the semicolon is a statement terminator rather than a line terminator.
You should declare your using statements like this
using(var Bar = new Foo())
{
}
Thus making your code:
using (FileStream SourceCode = new FileStream("thecode.exe", FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
}
Your using statement at the top has a ; at the end. A using block is used to ensure a Disposable resource is disposed at the end of the block. In this case, without { }, your using statement is kind of useless. Either your expand the block of code using { }, or you just declare the variable without the using statement. Hope this helps!
Related
All I need is for file1 and file2 to show the text inside the file. File1 is working great! File2 not so much. I believe there is something wrong with how I wrote file2 being read. Because I made a class so that I can make file2's text go to another file called outputfile2, and even that isn't working.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace RandomName
{
class Program
{
static void Main(string[] args)
{
string winDir =
"C:/Users/RandomPerson/Desktop/RandomName/bin/Debug/";
string fileName = "file1.txt";
StreamReader reader = new StreamReader(winDir + fileName);
string outputFileName = "upperfile" + fileName;
StreamWriter writer = new StreamWriter(outputFileName);
int n = 0;
string st = "";
string upperString = "";
int n2 = 0;
string st2 = "";
string upperString2 = "";
string fileName2 = "file2.txt";
StreamReader reader2 = new StreamReader(winDir + fileName2);
string outputFileName2 = "output" + fileName2;
StreamWriter writer2 = new StreamWriter(outputFileName2);
do
{
++n;
st = reader.ReadLine(); // read one line from disk file
Console.WriteLine("Line #" + n + ": " + st); // write to the console
writer.WriteLine(st); // write line to disk file instead, using WriteLine() method
upperString = upperString + "\n" + st; // append each line to the big string
}
while (!reader.EndOfStream);
do
{
++n2;
st2 = reader2.ReadLine(); // read one line from disk file
Console.WriteLine("Line #" + n2 + ": " + st2); // write to the
console
writer2.WriteLine(st2); // write line to disk file instead,
using WriteLine() method
upperString2 = upperString2 + "\n" + st2; // append each line
to the big string
}
while (!reader2.EndOfStream);
reader.Close();
writer.Close();
Console.WriteLine("\nHere is the entire file in a string:");
Console.WriteLine(upperString);
Console.WriteLine(upperString2);
UpperString b = new UpperString(upperString);
UpperString2 c = new UpperString2(upperString2);
Console.WriteLine("\nThe string in reverse case: ");
b.showReverseCase();
Console.WriteLine("\n");
c.readingFile2();
c.toNewFile2();
}
}
}
"b." is for another class that I have. I copied the code from that class into the "c." one, changing names of strings and such. And that didn't work. Which is why I think something is wrong somewhere in the main.
Here is the class
class UpperString2
{
private string upperString2;
public UpperString2() { }
public UpperString2(string c) { upperString2 = c; }
public void readingFile2()
{
string[] lines = System.IO.File.ReadAllLines("C:/Users/SomeName/Desktop/FolderName/bin/Debug/file2.txt");
System.Console.WriteLine("\nAnother Poem \n");
foreach (string line in lines)
{
// Use a tab to indent each line of the file.
Console.WriteLine(line);
}
}
public void toNewFile2()
{
using (StreamWriter writetext = new StreamWriter("outputfile2.txt"))
{
string newText = (upperString2.ToUpper()).ToString();
writetext.WriteLine(newText);
}
}
I am a bit new to SteamReader and SteamWriter, which is why I think I went wrong somehow with that. I'm not sure what though. Thank you anyone who can help me have the text in file2 show up without it being overwritten by file1's text!
The problem is "outputfile2" was already opened by reader2 in Main().
string fileName2 = "file2.txt";
StreamReader reader2 = new StreamReader(winDir + fileName2);
string outputFileName2 = "output" + fileName2; //<--outputfile2.txt
StreamWriter writer2 = new StreamWriter(outputFileName2)
Then it raises an exception when you try to open the same file for writting in toNewFile2():
public void toNewFile2()
{
using (StreamWriter writetext = new StreamWriter("outputfile2.txt"))
{
string newText = (upperString2.ToUpper()).ToString();
writetext.WriteLine(newText);
}
}
This happens because the object writer2 is still alive and locking the file in Main() and there's no using statement for disposing the object when no longer needed.
Since you have moved the code to a class, call that class instead.
So I got the IOException: Attempted to Seek before the beginning of the stream. But when I looked into it the seek statement was inside of a using statement. I might be missunderstanding the using() because as far as I knew this initializes the in this case filestream before running the encased code.
private string saveLocation = string.Empty;
// This gets called inside the UI to visualize the save location
public string SaveLocation
{
get
{
if (string.IsNullOrEmpty(saveLocation))
{
saveLocation = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + #"\Pastes";
Initializer();
}
return saveLocation;
}
set { saveLocation = value; }
}
And this is the function it calls
private void Initializer()
{
// Check if the set save location exists
if (!Directory.Exists(saveLocation))
{
Debug.Log("Save location did not exist");
try
{
Directory.CreateDirectory(saveLocation);
}
catch (Exception e)
{
Debug.Log("Failed to create Directory: " + e);
return;
}
}
// Get executing assembly
if (string.IsNullOrEmpty(executingAssembly))
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
executingAssembly = Uri.UnescapeDataString(uri.Path);
}
// Get the last received list
if (!string.IsNullOrEmpty(executingAssembly))
{
var parent = Directory.GetParent(executingAssembly);
if (!File.Exists(parent + #"\ReceivedPastes.txt"))
{
// empty using to create file, so we don't have to clean up behind ourselfs.
using (FileStream fs = new FileStream(parent + #"\ReceivedPastes.txt", FileMode.CreateNew)) { }
}
else
{
using (FileStream fs = new FileStream(parent + #"\ReceivedPastes.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
if (fs.Seek(-20000, SeekOrigin.End) >= 0)
{
fs.Position = fs.Seek(-20000, SeekOrigin.End);
}
using (StreamReader sr = new StreamReader(fs))
{
while (sr.ReadLine() != null)
{
storedPastes.Add(sr.ReadLine());
}
}
}
}
}
isInitialized = true;
}
Are the commentors have posted: the file is less than 20000 bytes. It seems like you assume that Seek will stay at position 0 if the file is not large enough. It doesn't. It throws ArgumentException in that case.
Another thing. Seek will move the position for you. No need to do both. Either use:
fs.Seek(-20000, SeekOrigin.End);
or set the position:
fs.Position = fs.Length - 20000;
So what you really wanted to write is:
if (fs.Length > 20000)
fs.Seek(-20000, SeekOrigin.End);
public void Convert_Xls_To_CSV(string sourceFile, string targetFile)
{
try
{
// wrtr = new StreamWriter(targetFile);
StreamWriter wrtr = new StreamWriter(new FileStream(targetFile, FileMode.Create, FileAccess.Write, FileShare.Read));
DataTable dt = ConvertExcelFileToDataTable(sourceFile);
for (int x = 0; x < dt.Rows.Count; x++)
{
string rowString = "";
for (int y = 0; y < dt.Columns.Count; y++)
{
rowString += "\"" + dt.Rows[x][y].ToString() + "\",";
}
wrtr.WriteLine(rowString);
}
wrtr.Close();
wrtr.Dispose();
}
catch (Exception ex)
{
Error_lb.Text = ex.Message;
}
}
I'm using this function to write a csvfile.the targetFile is not created.
StreamWriter wrtr = new StreamWriter(new FileStream(targetFile, FileMode.Create, FileAccess.Write, FileShare.Read));
should this line create the file if it's not exist ?
Simplify your call to;
sw = new StreamWriter(fileNameToSave, false)
From MSDN;
StreamWriter(String, Boolean) - Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.
Also, your usage seems similar to something I have some code for;
var saveFile = new SaveFileDialog();
saveFile.InitialDirectory = Properties.Settings.Default.systemLogPath;
saveFile.RestoreDirectory = true;
saveFile.Title = "Filename to log to";
saveFile.Filter = "Text (*.txt)|*.txt|Log (*.log)|*.log";
if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (var sw = new StreamWriter(saveFile.FileName, false))
{
foreach (var item in messages.Items)
{
sw.Write(item.ToString() + Environment.NewLine);
}
}
}
Maybe that can be of use to you as well.
Please read the documentation.
Your second parameter refers to the FileMode Enumeration which says the following about FileMode.Create:
Specifies that the operating system should create a new file. If the file already exists, it will be overwritten.
I found this program ( http://support.microsoft.com/kb/304655 ) where i compile the code during runtime, It works for code that uses the reference,
using System;
Following is the the code for the program that compiles code during runtime,
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
string Output = "Out.exe";
Button ButtonObject = (Button)sender;
textBox2.Text = "";
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
//Make sure we generate an EXE, not a DLL
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = icc.CompileAssemblyFromSource(parameters, textBox1.Text);
if (results.Errors.Count > 0)
{
textBox2.ForeColor = Color.Red;
foreach (CompilerError CompErr in results.Errors)
{
textBox2.Text = textBox2.Text +
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
//Successful Compile
textBox2.ForeColor = Color.Blue;
textBox2.Text = "Success!";
//If we clicked run then launch our EXE
if (ButtonObject.Text == "Run") Process.Start(Output);
}
And Following is the code i need to compile at runtime,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
namespace Tsubame
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(#"url");
// Create Client
WebClient client = new WebClient();
// Assign Credentials
client.Credentials = new NetworkCredential("user", "pass");
//Grab Data
var data = client.DownloadString(#"url");
JObject o = JObject.Parse(data);
string getFristRow = Convert.ToString(o["Body"][0]["RowId"]);
string encaplulateStart = "\\\"";
string encaplulateEnd = "\\\":";
List<string> _matches = new List<string>();
_matches = Regex.Matches(getFristRow, #"(?<=" + encaplulateStart + ").*(?=" + encaplulateEnd + ")")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
foreach (string head in _matches)
{
Console.WriteLine(head);
}
Console.ReadLine();
}
}
}
But when I input this gives the error code,
Error Number: CS0234
For the references other than System. May I please know how to add additional references during runtime so that it can compile sucessfully :) Thank you very much :)
You need to add the references in CompilerParameters using CompilerParameters.ReferencedAssemblies:
var parameters = CompilerParameters
{
GenerateExecutable = true,
OutputAssembly = Output,
ReferencedAssemblies = {
"System.dll",
"System.Core.dll",
// etc
}
};
(Of course you don't have to use object initializer syntax to set this up, but it makes it neater IMO.)
I have a php code like this and I need to convert it to .Net
$A = array_keys($_GET);
$f1 = fopen("doc\\outputreport.txt",'w');
for($i=0; $i<sizeof($A); $i++) {
$args = $A[$i]."=".konvertering($_GET[ $A[$i] ], "ISO8859-1", "UTF-8");
fwrite($f1, $args."\r\n");
}
Here is my conversion:
string fileOut = ((Request.QueryString["msisdn"] )+ (Request.QueryString["shortcode"]) + (Request.QueryString["password"]).ToString());
try
{
Filestream filestream = new Filestream(#"\\outputreport.txt", FileMode.Open, FileAccess.Write,FileMode.Append);
}
finally
{
}
}
Values comes from another page via a query string. In this file I write converted values.UTF-8 to ISO.I have another function called konvertering to convert characters from UTF 8 to ISO.but i'm not handle that part here..is this partial part correct ? how can i do that part.. give me a solution or clue
I think it works for you as per your question :
string fileOut = ((Request.QueryString["msisdn"] )+ (Request.QueryString["shortcode"]) + (Request.QueryString["password"]).ToString());
string mydocpath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StringBuilder sb = new StringBuilder();
foreach (string txtName in Directory.EnumerateFiles(mydocpath,"outputreport.txt"))
{
using (StreamReader sr = new StreamReader(txtName))
{
sb.AppendLine(fileOut);
sb.AppendLine("= = = = = =");
sb.Append(sr.ReadToEnd());
sb.AppendLine();
sb.AppendLine();
}
}
using (StreamWriter outfile =
new StreamWriter(mydocpath + #"\outputreport.txt"))
{
outfile.Write(sb.ToString());
}
I have never used PHP but if you are just trying to write to a file then it would probably be better to use
System.IO.File.AppendAllText(string path, string contents);