I use multiple file upload and I want to assign each file name with the global array called img using the foreach how can I do it in asp.net/c#?
string[] img={""};
foreach (string s in Request.Files) {
HttpPostedFile file = Request.Files[s];
int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = "";
if (!string.IsNullOrEmpty(fileName)) {
fileExtension = Path.GetExtension(fileName);
file.SaveAs(filename);
}
}
I would use a List<string> for this purpose:
List<string> img = new List<string>();
foreach (string s in Request.Files)
{
HttpPostedFile file = Request.Files[s];
int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = "";
if (!string.IsNullOrEmpty(fileName))
{
img.add(fileName);
fileExtension = Path.GetExtension(fileName);
file.SaveAs(filename);
}
Here is a great explanation on why List<T> is almost always better than using an array in C#: https://softwareengineering.stackexchange.com/a/221897
If you give us a little better explanation of what you're trying to accomplish, I could probably improve on this answer.
Related
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);
}
When user uploads multiple documents I am storing their files in my project like this:
Guid id;
id = Guid.NewGuid();
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(id + item.FileName));
item.SaveAs(filePath);
So files are saved like this in my project:
1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt
bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt
Now when creating zip files I am getting same name of this files when extracting zip files but I don't want guid in my file name after user downloads file.
However I have tried to remove guid from my file name but getting error System.IO.FileNotFoundException.
This is my code:
using (var zip = new ZipFile())
{
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" }; //file name are Log.txt and Logging.txt
string[] str1 = str .Split(',');
foreach (var item in str1)
{
string filePath = Server.MapPath("~/Uploads/" + item.Substring(36));//as guid are of 36 digits
zip.AddFile(filePath, "files");
}
zip.Save(memoryStream);//Getting error here
}
ZipFile is throwing an exception because it can't find the file on disk as you have given it a name of a file that does not exist (by doing a .Substring()). To make it work you would have to rename the file using File.Copy with your new file name and then give that same file name to Zip.AddFile().
var orgFileName = "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt";
var newFileName = orgFileName.Substring (36);
File.Copy (orgFileName, newFileName, true);
zip.AddFile (newFileName);
You should use archive and ArchiveEntry. The rough code snipets how to do it (i don't test it):
using(var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) {
{
//using(var zip = new ZipFile()) {
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" }; //file name are Log.txt and Logging.txt
//string[] str = str.Split(',');
foreach(var item in str) {
using(var entryStream = archive.CreateEntry("files/" + item.Substring(36)).Open()) {
string filePath = Server.MapPath("~/Uploads/" + item);
var content = File.ReadAllBytes(filePath);
entryStream.Write(content, 0, content.Length);
}
}
}
}
sample for using DotNetZip:
using (ZipFile zip = new ZipFile())
{
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" };
foreach(var item in str) {
string filePath = Server.MapPath("~/Uploads/" + item);
var content = File.ReadAllLines(filePath);
ZipEntry e = zip.AddEntry("files/" + item.Substring(36), content);
}
}
zip.Save(memoryStream);
}
Taking source from #kevin answer i have manage to solve this:
List<string> newfilename1 = new List<string>();
using (var zip = new ZipFile())
{
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" }; //file name are Log.txt and Logging.txt
string[] str1 = str .Split(',');
foreach (var item in str1)
{
string filePath = Server.MapPath("~/Uploads/" + item);
string newFileName = Server.MapPath("~/Uploads/" + item.Substring(36));
newfilename1.Add(newFileName);
System.IO.File.Copy(filePath,newFileName);
zip.AddFile(newFileName,"");
}
zip.Save(memoryStream);
foreach (var item in newfilename1)
{
System.IO.File.Delete(item);
}
}
I am trying to upload files with same names to the server using GUID, but its not working and is still replacing the old files, can anybody help me by telling where I am making the mistake?
here is y code to upload:
protected void btnAddExpenditure_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string FileName = FileUpload1.PostedFile.FileName;
if (File.Exists(FileName))
{
FileName = Guid.NewGuid() + FileName;
}
//check file Extension & Size
int filesize = FileUpload1.PostedFile.ContentLength;
if (filesize > (20 * 1024))
{
Label1.Text = "Please upload a zip or a pdf file";
}
string fileextention = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileextention.ToLower() != ".zip" && fileextention.ToLower() != ".pdf")
{
Label1.ForeColor = System.Drawing.Color.Green;
Label1.Text = "Please upload a zip or a pdf file";
}
else
{
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//save file to disk
FileUpload1.SaveAs(Server.MapPath("Reciepts/" + ReceiptFileName));
}
string FileName = FileUpload1.PostedFile.FileName;
if (File.Exists(FileName))
{
FileName = Guid.NewGuid() + FileName;
}
...
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
Here's your problem. You're creating a new string variable that holds the file name (FileName). If it exists, you modify FileName with a new GUID. But at the very end...
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
you're still using the original FileUpload1.PostedFile.FileName. This should be changed to
string ReceiptFileName = Path.GetFileName(FileName);
EDIT: Reading through the code again, I think you may have other problems as well. Assuming that FileUpload1.PostedFile.FileName is a full path (i.e. C:\Folder\File.txt), then
FileName = Guid.NewGuid() + FileName;
would result in something like 123-4321-GUIDC:\Folder\File.txt
I doubt that's what you want. You might want to flip that around
FileName = FileName + Guid.NewGuid();
this is my code in controller
public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
{
string TempPath = Server.MapPath("~/TempImages/");
foreach (HttpPostedFileBase file in files)
{
string filePath = Path.Combine(TempPath, file.FileName);
Tempdata["paths"] =filePath;
}
}
how in insert every time the path and get it as array / arraylist ?
update:
this is what really goes on for every image readed this action is running
public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
{
if (!Directory.Exists(Server.MapPath("~/TempImages/")) || files !=null)
{
string TempPath = Server.MapPath("~/TempImages/");
List<string> paths = new List< String> ();
foreach (HttpPostedFileBase file in files)
{
string filePath = Path.Combine(TempPath, file.FileName);
System.IO.File.WriteAllBytes(filePath, ReadData(file.InputStream));
file.SaveAs(filePath);
paths.Add(filePath);
TempData["paths"] = paths;
}
}
return view();
}
Can you not just do
public ActionResult UploadFiles(IEnumerable<HttpPostedFileBase> files)
{
List<string> paths = new List<string>();
foreach (HttpPostedFileBase file in files)
{
string filePath = Path.Combine(TempPath, file.FileName);
paths.Add (filePath);
}
Tempdata["paths"] = paths;
}
I need to create a SSIS script to remove the date from file name. for example file name is: TestFile_122413.CSV I need to rename it to TestFile.CSV. I don't know how to keep file extension and how to deal with the date changes on file. I receive this file every day. Here is my code:
`public void Main()
// TODO: Add your code here
const string DIRECTORY_PATH = #"E:\ScriptsTest";
//const string FILE_NAME_TEMPLATE = "SSS_PROF_010113.CSV";
const string FILE_NAME_TEMPLATE = "*.CSV";
if (Directory.Exists(DIRECTORY_PATH))
{
string[] filePathList = Directory.GetFiles(DIRECTORY_PATH);
foreach (string filePath in filePathList)
{
if (File.Exists(filePath))
{
File.Move(filePath, filePath.Replace(FILE_NAME_TEMPLATE, FILE_NAME_TEMPLATE.Substring(0,8)));
}
}
}
}`
This should work. BTW, have you tried using the ForEach task? That may be simpler.
public void Main()
{
const string DIRECTORY_PATH = #"C:\temp\";
const string FILE_NAME_TEMPLATE = "*_??????.CSV";
int underscoreAt = 0;
if (Directory.Exists(DIRECTORY_PATH))
{
string[] filePathList = Directory.GetFiles(DIRECTORY_PATH,FILE_NAME_TEMPLATE);
foreach (string filePath in filePathList)
{
if (File.Exists(filePath))
{
underscoreAt = filePath.LastIndexOf('_');
string newName = string.Format ("{0}.CSV", filePath.Substring(0, underscoreAt));
File.Move(filePath,newName );
}
}
}
}
Check out the SSIS File System Task. It has an operation to rename a file.
Here is a video on how it works.
Hope this helps!
Eric
Try this, it compiles but I haven't run it:
public class Foo
{
public void Main()
{
const string DIRECTORY_PATH = #"E:\ScriptsTest";
if (Directory.Exists(DIRECTORY_PATH))
{
string[] filePathList = Directory.GetFiles(DIRECTORY_PATH);
foreach (string filePath in filePathList)
{
if (File.Exists(filePath))
{
// Get the file name
string fileName = Path.GetFileName(filePath);
// Get the file extension
string fileExtension = Path.GetExtension(filePath);
// Get the file name without the date part
string fileTitle = fileName.Substring(0, fileName.IndexOf("_"));
File.Move(filePath, DIRECTORY_PATH + #"\" + fileTitle + "." + fileExtension);
}
}
}
}
}