I work with memory-mapped files and after I finish my work I want to delete the files from the disk. but I have the UnauthorizedAccessException in File.Delete(fileName); I've read here that I should use "using", but i work with several files so I have the array of MemoryMappedFileAccessor's.
my code:
var mmf_acc_array = new MemoryMappedViewAccessor[numFiles];
var size = 1048576; //1Mb
var mmf = new MemoryMappedFile[numFiles];
for (int i = 0; i < numFiles; i++)
{
mmf[i] = MemoryMappedFile.CreateFromFile(Path.Combine("tmp", "tmp" + i.ToString()));
mmf_acc_array[i] = mmf[i].CreateViewAccessor(0, size);
}
do sm work
for (int i = 0; i < numFiles; i++)
{
mmf_acc_array[i].Dispose();
mmf[i].Dispose();
File.Delete(Path.Combine("tmp", "tmp" + i.ToString()));
}
Exception arises in File.Delete(); How can I free the file?
Related
I have problem with memory.
I want do add pictures to my excel. Picuters are on azure blob.
After 1k of added pictures my program slowing so much till outofmemory exception.
I will paste my code here:
string filePath = #"excel.xlsx";
int i = 0;
public void Generate(int worksheetnumber)
{
using (FileStream fileStream = File.Open(filePath, FileMode.Open))
{
var package = new ExcelPackage(fileStream);
ExcelWorksheet workSheet = package.Workbook.Worksheets[worksheetnumber];
workSheet.Column(2).Width = 21;
workSheet.Column(4).Width = 21;
for (int j = workSheet.Dimension.Start.Row + 1; j <= workSheet.Dimension.End.Row; j++)
{
InsertImage(workSheet, j, 1);
InsertImage(workSheet, j, 3);
}
string path = string.Format(#"{0}.xlsx", worksheetnumber);
Stream stream2 = File.Create(path);
package.SaveAs(stream2);
stream2.Close();
}
}
private void InsertImage(ExcelWorksheet workSheet, int j, int columnNumber)
{
if (!string.IsNullOrEmpty(workSheet.Cells[j, columnNumber].Text))
{
try
{
var splittedUrlHash = workSheet.Cells[j, columnNumber].Text.Split('/');
using (var stream = DownloadBlobFileToStream(splittedUrlHash[1], splittedUrlHash[0], SHOP))
{
Image image = Image.FromStream(stream);
var picture = workSheet.Drawings.AddPicture(string.Format("{0}{1}", j, columnNumber+1), image);
stream.Close();
picture.From.Column = columnNumber;
picture.From.Row = j - 1;
picture.To.Column = columnNumber;
picture.To.Row = j - 1;
picture.SetSize(150, 120);
workSheet.Row(j).Height = 100;
Debug.WriteLine("Dodano obrazek - {0}", i);
i++;
}
}
catch (System.ArgumentException e)
{
}
}
}
I want to admit, I have a link images in Columns 1 and 3. Images are locating in cols 2 and 4.
Is there any solution to handle this error in this case without losing images, or leaving empty cells
How to Save multiple files in asp.net 4.0 by Fileupload Control with multiple fileupload control?
I have two fileupload control one for image and second for thumbimage. So I want to save multiple image and thumbimage ?
You are actually overwriting the fist file with the second one when you are in the loop. I would suggest you to create a list for the files and add to the list in the loop like below. You will then have a list of file when you can use firstOrDefault() for the first item as well as use Skip() and Take() to select any item you want.
HttpFileCollection uploadedFiles = Request.Files;
List<HttpPostedFile> fileList1 = new List<HttpPostedFile>();
List<HttpPostedFile> fileList2 = new List<HttpPostedFile>();
for (int i = 0; i < uploadedFiles.Count; i++)
{
HttpPostedFile hpf = uploadedFiles[i];
var hpfKey = uploadedFiles.Keys[i];
if (hpfKey.IndexOf("FileUpload1") > 0)
{
fileList1.Add(hpf);
}
if (hpfKey.IndexOf("FileUpload2") > 0)
{
fileList2.Add(hpf);
}
}
Update:
Now to get the first file you call FirstOrDefault() on the list like below:
fileList1.FirstOrDefault();
And to get the second file :
fileList1.Skip(1).FirstOrDefault();
HttpFileCollection uploadedFiles = Request.Files;
int i = uploadedFiles.Count;
List<HttpPostedFile> fileList1 = new List<HttpPostedFile>();
List<HttpPostedFile> fileList2 = new List<HttpPostedFile>();
if (i > 0)
{
for (int j = 0; j < i/2; j++)
{
fileList1.Add(uploadedFiles[j]);
}
}
if (i > 0)
{
for (int j = i / 2; j < i; j++)
{
fileList2.Add(uploadedFiles[j]);
}
}
int filecount = fileList1.Count;
if (filecount > 0)
{
for (int j = 0; j < filecount; j++)
{
string image = fileList1[j].FileName;
fileList1[j].SaveAs(imagepath);
string image = fileList2[j].FileName;
fileList2[j].SaveAs(imagepath);
}
}
I've created a for loop that creates n folders. I would like to create a text file in each folder. How do i do it?
for (int i = 1; i < 17; i++)
{
System.IO.Directory.CreateDirectory(
String.Format(#"C:\Users\xxx\Desktop\xx\Test{0:d2}", i));
}
I found a better solution.
for (int i = 1; i < 17; i++)
{
Directory.CreateDirectory(String.Format(#"C:\Users\xxx\Desktop\xx\Test"+i, i));
if (!File.Exists(string.Format(#"C:\Users\xxx\Desktop\xx\Test{0}/Test.txt", i)))
{
File.WriteAllText(string.Format(#"C:\Users\xxx\Desktop\xx\Test{0}/Test.txt", i), " ");
}
Try this
for (int i = 1; i < 17; i++)
{
var folder = System.IO.Directory.CreateDirectory(String.Format(#"C:\Users\xxx\Desktop\xx\Test{0:d2}", i));
System.IO.File.WriteAllText(folder.FullName + #"\WriteText.txt", "your text content");
}
Update
if you want more than one file
for (int i = 1; i < 17; i++)
{
var folder = System.IO.Directory.CreateDirectory(String.Format(#"C:\Users\xxx\Desktop\xx\Test{0:d2}", i));
System.IO.File.WriteAllText(folder.FullName + #"\WriteText1.txt", "your text content 1");
System.IO.File.WriteAllText(folder.FullName + #"\WriteText2.txt", "your text content 2");
}
Try this:
var desktop_path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
for (int i = 1; i < 17; i++)
{
var folder_path = System.IO.Path.Combine(desktop_path, String.Format(#"xx\Test{0:d2}", i));
var file_path = System.IO.Path.Combine(folder_path, "file.txt");
System.IO.Directory.CreateDirectory(folder_path);
System.IO.File.WriteAllText(file_path, "content");
}
This code finds the current user's desktop path, and then uses System.IO.Path.Combine to ensure that paths are correctly concatenated together.
for (int i = 1; i < 17; i++)
{
var dir = System.IO.Directory.CreateDirectory
(String.Format(#"C:\Users\xxx\Desktop\xx\Test{0:d2}", i));
System.IO.File.Create(dir.FullName+ #"\MyFile.txt");
}
To create add content on the file, we can use FileStream object returned by File.Create()
Try this above,
I hope this may easy for you
string path = #"d:\\dummyfolder";
for (int i = 0; i < 17; i++)
{
string _folderPath = string.Format("{0}\\{1}", path, i);
if (!Directory.Exists(_folderPath))
{
//creating folder
Directory.CreateDirectory(_folderPath);
//creating text file
string _filePath = string.Format("{0}\\{1}\\{1}.txt", path, i);
string text = i + " " + "Content of the text file ";
File.WriteAllText(_filePath, text);
}
}
On one of my WebPages I have placed FileUpload1 item, in which I would like to store CSV file and then analyze it. However I can't read it in, an Exception is thrown. It seems like the filepath changes (I have file store on Desktop, whereas it displays that the file is searched in C:\Program Files (x86)\IIS Express).
protected void Button2_Click(object sender, EventArgs
{
Response.Write("Jestem w petli file.hasfile");
if (FileUpload1.PostedFile != null)
{
string filePath = FileUpload1.PostedFile.FileName;
StreamReader reader = new StreamReader(filePath);
string[] readLines = new string[7];
int dayOfWeek = 0;
while (dayOfWeek < 7)
{
do
{
string textLine = reader.ReadToEnd();
readLines[dayOfWeek] = textLine;
}
while (reader.Peek() != -1);
dayOfWeek++;
}
for(int i = 0; i < 7; i++)
{
generateData(readLines[i], i);
}
reader.Close();
}
for(int i = 0; i < 7; i++)
{
TableRow tblRow = new TableRow();
Table1.Rows.Add(tblRow);
for (int j = 0; j < 2; j++)
{
TableCell tCell = new TableCell();
tCell.Text = positionsInWtr[i, j];
tblRow.Cells.Add(tCell);
}
}
}
Could you tell me what I am doing wrong?
Thanks in advance,
Kokos
I need to compare two folder contents based on
1.No of files
2.Size of files
3 date
and i got an error index out of bound exception in this piece of code
private void SeekFiles(string Root)
{
string[] Files = System.IO.Directory.GetFiles(Root);
string[] Folders = System.IO.Directory.GetDirectories(Root);
FileInfo File;
for(int i=0; i< Folders.Length; i++)
{
File = new FileInfo(Files[i]);
FolderSize += File.Length;
}
for(int i=0; i< Folders.Length-1; i++)
{
SeekFiles(Folders[i]);
}
}
Any Suggestion??
Looks like you are using wrong index on a wrong collection :
for(int i=0; i< Folders.Length; i++)
{
File = new FileInfo(Files[i]);
FolderSize += File.Length;
}
Should be :
for(int i=0; i< **Files.Length**; i++)
{
File = new FileInfo(Files[i]);
FolderSize += File.Length;
}
You are using Files[i] but i < Folders.Length in the first for.
for(int i=0; i< Folders.Length; i++)
{
File = new FileInfo(Files[i]);
FolderSize += File.Length;
}
This should be Files.Length