I With Code my application added to startup
how I can after Creation File (filename + ".url") Change To (filename + ".exe")
static string filename = "troj";
public static string tempure = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\" + filename + ".exe";
public static string tempurepath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\";
public static void addtostart()
{
try
{
string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
if (System.IO.File.Exists(deskDir + "\\" + filename + ".url")) return;
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(deskDir + "\\" + filename + ".url"))
{
string app = tempure;
writer.WriteLine("[InternetShortcut]");
writer.WriteLine("URL=file:///" + app);
writer.WriteLine("IconIndex=0");
string icon = app.Replace('\\', '/');
writer.WriteLine("IconFile=" + icon);
writer.Flush();
}
}
catch
{
Related
I am trying to decompress a .s file programmatically using c#. I have tried using all the possible methods I know but couldn't decompress it. My actual file would be a file.tar.gz, I have uncompressed .tar.gz using ICSharpCode.SharpZipLib.Tar and ICSharpCode.SharpZipLib.GZip. In my uncompressed folder I would be having different files with "file_1.s" format. Can someone guide me plz?
Here is my function for decompressing:
public void ExtractTGZ(String gzArchiveName, String destFolder)
{
Stream inStream = File.OpenRead(gzArchiveName);
Stream gzipStream = new GZipInputStream(inStream);
TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
tarArchive.ExtractContents(destFolder);
tarArchive.Close();
gzipStream.Close();
inStream.Close();
}
public void ExtractTar(String tarFileName, String destFolder)
{
Stream inStream = File.OpenRead(tarFileName);
TarArchive tarArchive = TarArchive.CreateInputTarArchive(inStream);
tarArchive.ExtractContents(destFolder);
tarArchive.Close();
inStream.Close();
}
When a button event Occurs it will select the file.tar.gz from windows explorer and with next button it will start decompressing and its code is as shown below:
private void OpenFileLocationEvent(object sender, EventArgs e)
{
if (openLogs.ShowDialog() == DialogResult.OK)
{
tbTargetFile.Text = openLogs.FileName;
}
}
private void StartAnalysis(object sender, EventArgs e)
{
if (tbTargetFile.TextLength > 5)
{
//MessageBox.Show("Source File:" + tbTargetFile.Text + " ExtrctdDirectory:" + nextDirectory);
_uc.ExtractTGZ(tbTargetFile.Text, nextDirectory);//Extract .tar.gz
string[] files = Directory.GetFiles(nextDirectory, "*.s");
string filename = "";
string targetFile = "";
string newFile = "";
int count = 0;
foreach (string f in files)
{//Changing File Type
filename = Path.GetFileName(f);
targetFile = nextDirectory + "//" + filename;
newFile = nextDirectory + "//File_" + count + ".tar";
File.Move(targetFile, newFile);
count += 1;
//FileInfo finfo = new FileInfo(targetFile);
//finfo.MoveTo(Path.ChangeExtension(targetFile, ".txt"));
}
string[] tarfiles = Directory.GetFiles(nextDirectory, "*.tar");
foreach (string f in tarfiles)
{
filename = Path.GetFileName(f);
targetFile = nextDirectory + "\\" + filename;
MessageBox.Show("Traget File:" + targetFile + " ExtrctdDirectory:" + extrctdDirectory);
_uc.ExtractTar(targetFile, extrctdDirectory);
//_uc.ExtractTarByEntry(targetFile, extrctdDirectory, false);
//ZipFile.ExtractToDirectory(targetFile, extrctdDirectory);
}
}
}
Using a 7zip console application solved my problem. And this is my code.
private void StartAnalysis(object sender, EventArgs e)
{
if (tbTargetFile.TextLength > 5)
{
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = "7za.exe";
p.Arguments = "x \"" + tbTargetFile.Text + "\" -o\"" + nextDirectory + "\"";
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();
string[] files = Directory.GetFiles(nextDirectory, "*.tar");
string filename = "";
string targetFile = "";
foreach (string f in files)
{
filename = Path.GetFileName(f);
targetFile = nextDirectory + "\\" + filename;
}
p.Arguments = "x \"" + targetFile + "\" -o\"" + nextDirectory + "\"";
p.WindowStyle = ProcessWindowStyle.Hidden;
x = Process.Start(p);
x.WaitForExit();
targetFile = nextDirectory + "\\*.s";
p.Arguments = "x \"" + targetFile + "\" -o\"" + extrctdDirectory + "\"";
p.WindowStyle = ProcessWindowStyle.Hidden;
x = Process.Start(p);
x.WaitForExit();
}
}
I have an error with database file path, the project has many databases with 10 tables, for each file should have 1 database, I create a database but it can't be saved as file ... and the error is:
The File Path Is Not Supported ...
public class filewrite
{
public string datadress, dataname, databaseadress, tablexist, dsname, databak, dataldf, databakldf, filepath, filename;
public filewrite()
{
databaseadress = "baseadress";
dataname = "name";
datadress = "adress";
dsname = "databasename1";
databak = "backUp";
tablexist = "yesorno";
dataldf = "dl";
databakldf = "dbl";
filepath = "path";
filename = "name";
}
public byte writing()
{
if (File.Exists(filepath + #"\" + filename + #"\Data" + datadress))
File.Delete(filepath + #"\" + filename + #"\Data" + datadress);
if (File.Exists(#"C:\tempFile.SMP"))
File.Delete(#"C:\tempFile.SMP");
string path = filepath + #"\" + filename + #"\Data" + datadress;
FileStream fpath = File.Create(path);(The error is in here)
try
{
// read from file or write to file
StreamWriter fwrite = new StreamWriter(fpath);
fwrite.WriteLine(datadress);
fwrite.WriteLine(dataname);
fwrite.WriteLine(databaseadress);
fwrite.WriteLine(tablexist);
fwrite.WriteLine(dsname);
fwrite.WriteLine(databak);
fwrite.WriteLine(dataldf);
fwrite.WriteLine(databakldf);
fwrite.Close();
}
finally
{
}
File.Copy(filepath + #"\" + filename + #"\Data" + datadress, #"C:\tempFile.SMP");
return 10;
}
}
Rather than using filepath + #"\" + filename + #"\Data" + datadress;,
Try using System.IO.Path.Combine instead:
Path.Combine(filepath, fileName, Data, datadress);
which returns a string.
I'm using Streamwriter to save my list data to a text file, but the file is always empty when I open it.
I can get the list to display all of the inputs, so the list works. Heres the code for the filewriter.
private void SaveToFile()
{
string taxpayerLine;
string taxpayerFile;
string myFileName;
FileInfo myFile;
SaveFileDialog taxpayerFileChooser;
StreamWriter fileWriter;
taxpayerFileChooser = new SaveFileDialog();
taxpayerFileChooser.Filter = "All text files|*.txt";
taxpayerFileChooser.ShowDialog();
taxpayerFile = taxpayerFileChooser.FileName;
taxpayerFileChooser.Dispose();
fileWriter = new StreamWriter(taxpayerFile, true);
foreach (Taxpayer tp in Taxpayers)
{
taxpayerLine = tp.Name + "," +
tp.Salary.ToString() + "," +
tp.InvestmentIncome.ToString() + "," +
(tp.InvestmentIncome + tp.Salary).ToString() + "," +
tp.GetRate().ToString() + "," +
tp.GetTax().ToString();
fileWriter.WriteLine(taxpayerLine);
}
fileWriter.Close();
fileWriter.Dispose();
myFile = new FileInfo(taxpayerFile);
myFileName = myFile.Name;
MessageBox.Show("Data Saved to " + myFileName);
}
You can try changing your code like this:
private void SaveToFile()
{
string taxpayerLine;
string taxpayerFile = string.Empty;
string myFileName;
FileInfo myFile;
using (SaveFileDialog taxpayerFileChooser = new SaveFileDialog())
{
taxpayerFileChooser.Filter = "All text files|*.txt";
if (DialogResult.OK == taxpayerFileChooser.ShowDialog())
{
taxpayerFile = taxpayerFileChooser.FileName;
}
}
if (!string.IsNullOrEmpty(taxpayerFile))
{
using (StreamWriter fileWriter = new StreamWriter(taxpayerFile, true))
{
foreach (Taxpayer tp in Taxpayers)
{
taxpayerLine = tp.Name + "," +
tp.Salary.ToString() + "," +
tp.InvestmentIncome.ToString() + "," +
(tp.InvestmentIncome + tp.Salary).ToString() + "," +
tp.GetRate().ToString() + "," +
tp.GetTax().ToString();
fileWriter.WriteLine(taxpayerLine);
}
}
myFile = new FileInfo(taxpayerFile);
myFileName = myFile.Name;
MessageBox.Show("Data Saved to " + myFileName);
}
else
{
MessageBox.Show("Data not saved");
}
}
The using statement explicit calls the Dispose() method of disposable objects after the block execution. http://msdn.microsoft.com/en-us/library/yh598w02.aspx
I know others had a similar problem but my problem is specific for image...
I have an image function like below:
static public string Setimage(PictureBox pictureBox, OpenFileDialog ofd,string nameform,string folderform)
{
ofd.Title = "Select Pictures";
ofd.Filter = "Pictures(*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png | All file (*.*)| *.*";
ofd.DefaultExt = ".jpg"; // Default file extension
string namefile = "";
// Process open file dialog box results
if (ofd.ShowDialog() == DialogResult.OK)
{
// try
//{
string fileName = ofd.FileName;
if (ofd.SafeFileName.Length <= 50)
if (Image.FromFile(fileName).Width >= 640 && Image.FromFile(fileName).Height >= 480)
{
namefile = ofd.SafeFileName;
if (namefile != "Null_0_Null" || namefile != null)
{
string oldPath = #ofd.FileName;
string newFileName = namefile;
newpath = Application.StartupPath + #"\userpictures\" + #"Apartment\";
deladdress = newpath + folderform + #"\" + #newFileName;
Random rand = new Random();
string pp=newpath+folderform;
// string pdest;
#region Check Directory And File To copy
if (Directory.Exists(newpath + folderform))
{
if (!File.Exists(newpath + folderform + #"\" + #newFileName))
File.Copy(oldPath, newpath + folderform + #"\" + #newFileName);
// else
// {
// File.Delete(newpath + folderform + #"\" + #newFileName);
// File.Copy(oldPath, newpath + folderform + #"\" + #newFileName);
//}
}
else
{
Directory.CreateDirectory(newpath + folderform);
File.Copy(oldPath, newpath + folderform + #"\" + #newFileName);
}
#endregion
pictureBox.BackgroundImage = Image.FromFile(newpath + folderform + #"\" + #newFileName);
}
else { MessageBox.Show("filename" + namefile + "Not valid"); }
}
else { MessageBox.Show("Size of file not valid"); }
else { MessageBox.Show("size of name file not valid"); }
// }
// catch { MessageBox.Show("your file that you selected is not valid please select anyone."); }
}
return namefile;
}
For loading image I have this function:
static public void loadimage(PictureBox pictureBox, string img, string nameform, string folderform)
{
try
{
if (img != "Null_0_Null")
if (!System.IO.File.Exists(Application.StartupPath + #"\userpictures\" + nameform + #"\" + folderform + #"\" + img))
{
pictureBox.BackgroundImage = Image.FromFile(Application.StartupPath + "\\filepictures\\default4.PNG");
}
else
{
pictureBox.BackgroundImage =Image.FromFile(Application.StartupPath + #"\userpictures\" + nameform + #"\" + folderform + #"\" + img);
}
}
catch { }
}
In my form I call this functions. For set image I write a private string in my form:
string img1;
And for loading image in my form load write this:
loadimage(pictureBox1, "Blue hills.jpg","me", "Apartment");
img1 = "Blue hills.jpg";
For Setimage I have this:
img1=Setimage(pictureBox1, openFileDialog1,"me", "Apartment");
And when I use this code for delete image show me error "process can not be access ..."
System.IO.File.Delete("image path");
When you use Image.FromFile, that will open a file handle to that file and keep it open until the image is disposed.
You should:
Only call Image.FromFile once and reuse the object in Setimage (you're loading it twice in a single if condition...)
Dispose of every Image when you're done with it
Dispose of the old BackgroundImage before you set the new one
So long as you dispose of every Image which is related to the file before you delete the file, you should be okay.
I wanted to write a text to file using StreamWriter.But Filename should be current date name.
here is my coding.Can somebody tell me how to specify the file creation path?
Code Edit :
In here i wanted to create a .txt file but in here file not created.
public void WriteToFile( string name, string source, int dest, string messageIn, string operatorNew)
{
string directory = ResolveUrl("~/DesktopModules/SMSFunction/SMSText");
string filename = String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now,name);
string path = Path.Combine(directory, filename);
if (!File.Exists(filename))
{
using (StreamWriter str = File.CreateText(path))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
else if (File.Exists(filename))
{
using (var str = new StreamWriter(filename))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
you need to make following changes
1.Replace ResolveUrl with Server.MapPath
string directory = Server.MapPath("~/DesktopModules/SMSFunction/SMSText");
2.Add the file extension .txt as shown below
string filename = String.Format("{0:yyyy-MM-dd}__{1}.txt", DateTime.Now,name);
3.when you are checking whether file exists or not provide the path of the file , instead of filename
File.Exists(path);
4.under the else if block , here also provide the path , instead of filename
var str = new StreamWriter(path));
putting all together the code looks like,
string directory = Server.MapPath("~/DesktopModules/SMSFunction/SMSText");
string filename = String.Format("{0:yyyy-MM-dd}__{1}.txt", DateTime.Now, name);
string path = Path.Combine(directory, filename);
if (!File.Exists(path))
{
using (StreamWriter str = File.CreateText(path))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
else if (File.Exists(path))
{
using (var str = new StreamWriter(path))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
File.Create returns FileStream, and you need StreamWriter. You'll have to use its constructor that accepts Stream:
using (var str = new StreamWriter(File.CreateText(path)))
Simplify, use FileStream to create or overwrite your file (see below) depending on your neeeds you might want to change the FileMode to be something else (Append ?)
public void WriteToFile(string name, string source, int dest, string messageIn, string operatorNew)
{
string directory = ResolveUrl("~/DesktopModules/SMSFunction/SMSText");
string filename = String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now,name);
string path = Path.Combine(directory, filename);
using (FileStream fs = new FileStream(path, FileMode.Create))
{
using (StreamWriter str = new StreamWriter(fs))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
}
Let's say your console app project name is DataPrep. Now you can write in Data directory location by creating a new file namely as db.json
string filePath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, #"..\..\..\")) + #"Data\db.json";
if (!File.Exists(filePath))
{
using (StreamWriter _streamWriter = File.CreateText(filePath))
{
_streamWriter.Write(resultAll);
_streamWriter.Flush();
}
}
else if (File.Exists(filePath))
{
using (var _streamWriter = new StreamWriter(filePath))
{
_streamWriter.Write(resultAll);
_streamWriter.Flush();
}
}