Im trying to write a console application in order to store a single image from a given path into a new directory as suggested in this article. Despite my program not throwing out any errors the image I want to download just won't show up in my folder. I guess that's because I never told my program where I want the file to be saved? However, I haven't found anything clarifying this particular problem I have right now. I already referred to this and this question, too.
using System;
using System.IO;
using System.Net;
namespace GetImages
{
class Program
{
static void Main(string[] args)
{
string dirPath = #"C:\Users\Stefan\Desktop\Images";
try
{
// Create a new directory
DirectoryInfo imageDirectory = Directory.CreateDirectory(dirPath);
Console.WriteLine($"Directory '{Path.GetFileName(dirPath)}' was created successfully in {Directory.GetParent(dirPath)}");
// Image I'm trying to download from the web
string filePath = #"http://ilarge.lisimg.com/image/12056736/1080full-jessica-clements.jpg";
using (WebClient _wc = new WebClient())
{
_wc.DownloadFileAsync(new Uri(filePath), Path.GetFileName(filePath));
_wc.Dispose();
}
Console.WriteLine("\nFile successfully saved.");
}
catch(Exception e)
{
while (e != null)
{
Console.WriteLine(e.Message);
e = e.InnerException;
}
}
if (System.Diagnostics.Debugger.IsAttached)
{
Console.WriteLine("Press any key to continue . . .");
Console.ReadKey(true);
}
}
}
}
Edit: After some time I figured out that the file is saved in "C:\Users\Stefan\Documents\Visual Studio 2017\Projects\GetImages\GetImages\bin\Debug". But how do I get the file to be saved directly to dirPath without moving them from Debug to dirPath separately? My next step would be extending this program to save multiple files at once.
The second argument of DownloadFileAsync is the save location so combine the path you create and the filename from the URL:
_wc.DownloadFileAsync(new Uri(filePath), Path.Combine(dirPath, Path.GetFileName(filePath)));
Try this:
using (WebClient _wc = new WebClient())
{
_wc.DownloadFileAsync(new Uri(filePath), Path.Combine(dirPath,Path.GetFileName(filePath)));
}
Related
Finally got my code working fine, but I need to extract the most recent zipped file within the directory.
Really not sure how to go about this, can someone please point me in the correct direction, was thinking of using modified date and time, please see my code below...
using System;
using System.IO;
using System.IO.Compression;
namespace unZipMe
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo file = new DirectoryInfo(#"c:\Temp\ZipSampleExtract");
if(file.Exists)
{
file.Delete(true);
}
string myDir = (#"c:\Temp\ZipSampleExtract");
bool exists = System.IO.Directory.Exists(myDir);
if (!exists)
{
System.IO.Directory.CreateDirectory(myDir);
}
//provide the folder to be zipped
//string folderToZip = #"c:\Temp\ZipSample";
//provide the path and name for the zip file to create
string zipFile = #"c:\Temp\ZipSampleOutput\MyZippedDocuments.zip";
//call the ZipFile.CreateFromDirectory() method
//ZipFile.CreateFromDirectory(folderToZip, zipFile, CompressionLevel.Optimal, false);
//specif the directory to which to extract the zip file
string extractFolder = #"c:\Temp\ZipSampleExtract\";
//call the ZipFile.ExtractToDirectory() method
ZipFile.ExtractToDirectory(zipFile, extractFolder);
}
}
}
I'm fairly new to C# and what I'm trying to do is
Search for a file
List all matching files into a listbox
Copy the whole folder where the file is located to another place
I found bits and pieces on the web that I'm using. Right now it's only the btn_search_Click part that is working.
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_search_Click(object sender, EventArgs e)
{
try
{
listBox1.Items.Clear();
//Directory to search in
DirectoryInfo Di = new DirectoryInfo(#"D:\xxxx\Versionen");
FileInfo[] nPfad = Di.GetFiles(textBox1.Text, SearchOption.AllDirectories);
Int32 nLengePfad = nPfad.GetLength(0);
listBox1.Items.AddRange(nPfad);
}
catch (Exception)
{
MessageBox.Show("File not found");
}
}
private void btn_save_Click(object sender, EventArgs e)
{
{
string sourceFile = #"D:\Users\Public\public\test.txt";
string destinationFile = #"D:\Users\Public\private\test.txt";
// To move a file or folder to a new location:
System.IO.File.Move(sourceFile, destinationFile);
// To move an entire directory. To programmatically modify or combine
// path strings, use the System.IO.Path class.
System.IO.Directory.Move(#"C:\Users\Public\public\test\", #"C:\Users\Public\private");
}
}
}
}
My question now is, what would the code look like, if I want to select a file from the listbox and copy NOT the file but the folder it's located in to another place. I already have set a btn_save and a basic code to move files, but I need someone to show me a way to copy any selected file from the listbox or rather copy the folder of the selected file.
I'm fairly new to C# and am open for new approaches. If I'm completely wrong with the code, scratch it, show me a correct or easier way to achieve the same
You can move directly the directory with Directory.Move.
Using the FileInfo.DirectoryName you can get the Directory path from the FileInfo[] SelectedItems.
var itemsToMove = myListBox.SelectedItems.Cast<FileInfo>();
var directoriesTheyAreIn = itemsToMove.Select(x => x.DirectoryName);
var cleanDirectoriesList = directoriesTheyAreIn.Distinct();
//As many file can be in the same Dir we only need to move the dire once to move those file.
But what if Dir contains both selected and unselected files? Here I will move them all.
foreach (var path in cleanDirectoriesList)
{
// here you have to craft your destination directory
string destinationDirectory = "";
Directory.Move(path, destinationDirectory);
}
From your question it's unclear what part of the old path should be keep in the new path. but if it's based on your "D:\xxxx\Versionen" string you can simply replace this part with the new root path "NewRoot\foo\bar":
string destinationDirectory = path.Replace(#"D:\xxxx\Versionen", #"G:\FooBAR\NEWPATH\");
If you need to move only the selected file you can blindly call Directory.CreateDirectory before copying each file, as it won't throw error if the directory already exist. Grouping on directory to avoid useless instruction could have been possible but I feel like it won't be that easy to modify. Here the code will simply be: create the directory then move the file.
foreach (var item in itemsToMove) {
string destinationDirectory = #"BasedPath\" + " Craft it ";
Directory.CreateDirectory(destinationDirectory);
File.Move(item.FullName, destinationDirectory + item.Name);
}
Store the list of files into a List<FileInfo> and iterate through with foreach. This worked for me:
string destination = #"C:\Some\Destination\";
string actualFile = string.Empty;
foreach (var file in fileList)
{
actualFile = file.FullName;
File.Copy(actualFile, destination + Path.GetFileName(actualFile));
}
I am trying to write a file on button click event but getting an unauthorized error when trying to do so.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
{
string path = #"c:\program files\MyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
}
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
Getting the error by:
using (StreamWriter sw = File.CreateText(path))
Not sure what i am doing wrong? Could someone please help?
Thanks
By default in Windows a user or a programm started by a user can't write files to every location on a Windows pc.
Maybe try saving your file to a different location.
If that doesn't cut it for you, then you may need to look into running your programm at an elevated permission level
If you just want to save a file for your application the tippical place to do so would be the AppData Folder. The tipcal way of getting its path goes somthing like this:
string path=Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)+"/MyApplicationFolder";
You should change your path to authorize folder like :
string path=Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
In my application there is a situation like this.Before creating a file, my application search for files in a directory under a particular filename. If any file/files found, then it should read each files contents and write these contents(of each file) to a new file. I have googled many and tried some like this:
string temp_file_format = "ScriptLog_" + DateTime.Now.ToString("dd_MM_yyyy_HH");
string[] files = Directory.GetFiles(path,temp_file_format);
foreach (FileAccess finfo in files)
{
string text = File.ReadAllText(finfo);
}
and
System.IO.DirectoryInfo dir = new DirectoryInfo(path);
System.IO.FileInfo[] files = dir.GetFiles(temp_file_format);
foreach (FileInfo finfo in files)
{
finfo.OpenRead();
}
But all these failed..Can anyone show me an alternative for this?
Is there anything wrong in my temp_file_format string?
It will be nice if I could prepend these contents to the new file. Else also, no worries..
any help would be really appreciated..
This is a compete working implementation that does all of that
without reading everything in memory at one time (which doesn't work for large files)
without keeping any files open for more than the required time
using System.IO;
using System.Linq;
public static class Program {
public static void Main()
{
var all = Directory.GetFiles("/tmp", "*.cpp")
.SelectMany(File.ReadAllLines);
using (var w = new StreamWriter("/tmp/output.txt"))
foreach(var line in all)
w.WriteLine(line);
}
}
I tested it on mono 2.10, and it should work on any .NET 4.0+ (for File.ReadAllLines which is a lazy linewise enumerable)
Here's a short snippet that reads all the files and out puts them to the path outputPath
var lines = from file in Directory.GetFiles(path,temp_file_format)
from line in File.ReadAllLines(file)
select line;
File.WriteAllLines(outputPath, content);
The problem you are having with your code is not really related to reading files but simply trying to use an object as a type it's not. Directory.GetFiles returns an array of string and File.ReadXXX and File.OpenRead expects the path as a string. So you simply need to pass each of the strings returned as the path argument to the appropriate method. The above is one such example. Hope it helps both solve your problem and explain the actually issue with your code
try this:
foreach (FileInfo finfo in files)
{
try
{
using (StreamReader sr = new StreamReader("finfo "))
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
using (var output = File.Create(outputPath))
{
foreach (var file in Directory.GetFiles(InputPath,temp_file_format))
{
using (var input = File.OpenRead(file))
{
input.CopyTo(output);
}
}
}
how to create a file in c drive using C# in Windows7 OS
The following sample code will create a folder and a subfolder on your C: drive, and then create a new file in the subfolder with a random file name. Finally, some data will be written to the file. (The code is well-commented, and you should be able to figure out what's going on by studying it carefully.)
public class CreateFileOrFolder
{
static void Main()
{
// Specify a "currently active folder"
string activeDir = #"c:\testdir2";
//Create a new subfolder under the current active folder
string newPath = System.IO.Path.Combine(activeDir, "mySubDir");
// Create the subfolder
System.IO.Directory.CreateDirectory(newPath);
// Create a new file name. This example generates a random string.
string newFileName = System.IO.Path.GetRandomFileName();
// Combine the new file name with the path
newPath = System.IO.Path.Combine(newPath, newFileName);
// Create the file and write to it.
// DANGER: System.IO.File.Create will overwrite the file
// if it already exists. This can occur even with random file names.
if (!System.IO.File.Exists(newPath))
{
using (System.IO.FileStream fs = System.IO.File.Create(newPath))
{
for (byte i = 0; i < 100; i++)
{
fs.WriteByte(i);
}
}
}
// Read data back from the file to prove that the previous code worked.
try
{
byte[] readBuffer = System.IO.File.ReadAllBytes(newPath);
foreach (byte b in readBuffer)
{
Console.WriteLine(b);
}
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
See all the gory details by reading the original MSDN How-To article.