I want to upload a file in azure using C#.net no matter what format it will be. I want to check whether the file exists or not. If it exists then create a folder dynamically to save the uploaded file.
How can I pass another parameter which will check if the uploaded file exists or not, then if it exists, then create a subfolder in the Uploads folder to save it?
public UploadedFile Upload(Stream Uploading)
{
try
{
string filename = Guid.NewGuid().ToString() + ".png";
string FilePath = Path.Combine(HostingEnvironment.MapPath("~/Uploads"), filename);
UploadedFile upload = new UploadedFile
{
FilePath = FilePath
};
int length = 0;
using (FileStream writer = new FileStream(upload.FilePath, FileMode.Create))
{
int readCount;
var buffer = new byte[8192];
while ((readCount = Uploading.Read(buffer, 0, buffer.Length)) != 0)
{
writer.Write(buffer, 0, readCount);
length += readCount;
}
}
upload.FileLength = length;
return new UploadedFile { FilePath = "/Uploads/" + filename };
}
catch (Exception ex)
{
_logger.Error("Error Occured in Upload", ex);
ErrorData errorData = new ErrorData("Error Occured ", ex.Message);
throw new WebFaultException<ErrorData>(errorData, HttpStatusCode.OK);
}
}
Before you upload the file check if the same file name exists in the path. You can check if file exists using below code
//Read the path of your file
string curFile = #"c:\temp\test.txt";
Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");
https://msdn.microsoft.com/en-us/library/system.io.file.exists%28v=vs.110%29.aspx
Related
I want to create a folder directory and in that folder, I want to save the image and get the response. but when I check manually using file explorer the folder is not showing.
//take picture code
string DirName = "Sample";
string ImgName = "image.jpg";
string basepath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures);
takePhoto.Clicked += async (sender, args) =>
{
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("No Camera", ":( No camera available.", "OK");
return;
}
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
});
byte[] imageArray = null;
if (file != null)
{
using (MemoryStream ms = new MemoryStream())
{
var stream = file.GetStream();
stream.CopyTo(ms);
imageArray = ms.ToArray();
}
}
Stream data = new MemoryStream(imageArray);
if (file == null)
return;
filePath = file.Path;
paths.Enqueue(filePath);
var result = await CrossEDFSTemplate.Current.SaveFile(basepath, DirName,ImgName, filePath);
await DisplayAlert("Succesful", result.ToString(), "ok");
//Directory create code
public async Task<SaveFileResponse> SaveFile(string FolderBasePath, string FolderName, string
FileName, string FileFullPath = null, Stream data = null)
{
SaveCompletionSource = new TaskCompletionSource<SaveFileResponse>();
if (FolderBasePath != null && FolderName != null)
{
var directoryPath = Path.Combine(FolderBasePath, FolderName);
string NemFilePath = Path.Combine(directoryPath, FileName);
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
if (FileFullPath != null)
{
var imageData = File.ReadAllBytes(FileFullPath);
File.WriteAllBytes(NemFilePath, imageData);
}
else if (data != null)
{
byte[] bArray = new byte[data.Length];
using (FileStream fs = new FileStream(NemFilePath, FileMode.OpenOrCreate))
{
using (data)
{
data.Read(bArray, 0, (int)data.Length);
}
int length = bArray.Length;
fs.Write(bArray, 0, length);
}
}
else
{
var ResponseSaved = new SaveFileResponse("There are no items to Save", null, FileName);
SaveFileError(this, ResponseSaved);
SaveCompletionSource.TrySetResult(ResponseSaved);
}
}
else
{
return await SaveCompletionSource.Task;
}
return await SaveCompletionSource.Task;
}
according to this code, the directory is creating but when I manually checking that folder using file explorer the folder is not showing.
The path Environment.SpecialFolder.MyPictures you used to save the file is internal storage.
In Internal Storage, you couldn't see the files without root permission.
But you could use the code to check the file exist or not in the internal storage.
if (File.Exists(filepath))
{
}
If you want to view it, you could use adb tool. Please check the way in link.
How to write the username in a local txt file when login success and check on file for next login?
how to delete a zip file after copying into another folder...I am getting exception while deleting..It is saying that "The file is being used by another process".
string pathString1 = FullFilePath;
string sourceFileName = Path.GetFileName(pathString1);
string foldername = Path.GetDirectoryName(pathString1);
string pathString = Path.Combine(foldername, "Uploaded");
if (!System.IO.Directory.Exists(pathString))
{
System.IO.Directory.CreateDirectory(pathString);
string destFile = System.IO.Path.Combine(pathString, sourceFileName);
File.Copy(pathString1, destFile);
File.Delete(pathString1);
File.Delete(FileName);
}
If you decompress the zip-file, then do this in a using block or .Dispose() the object that is responsible for decompressing. What lib are you using?
To prevent the locking of files, the using statement will release the file when it's done with the operation:
using (FileStream stream = File.Open("path to file", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
...
}
Then again, if you're deleting the file right after you copy it, then why not just move it?
File.Move(from, to);
since there is this theory that a virus checker goes into your .zip file, you could re-try waiting for it to finish with retries
string pathString1 = FullFilePath;
string sourceFileName = Path.GetFileName(pathString1);
string foldername = Path.GetDirectoryName(pathString1);
string pathString = Path.Combine(foldername, "Uploaded");
if (!System.IO.Directory.Exists(pathString))
{
System.IO.Directory.CreateDirectory(pathString);
string destFile = System.IO.Path.Combine(pathString, sourceFileName);
File.Copy(pathString1, destFile);
int itries = 0;
int maxtries = 30; //suitable time of retrying
while (itries++ < maxtries)
{
try
{
File.Delete(pathString1);
itries = 999999;
}
catch (Exception ex)
{
if (itries > maxtries) throw ex;
Thread.Sleep(1000);
}
}
//File.Delete(FileName);
}
Requirement:
1) creating split zips file in multiple segments(say size - 1 GB/500 MB), so that they can be downloaded through browser. The total zip volume of all the segments could exceed 10 GB
2) the zip content could be multiple files or a folder containing sub folders and files
3) the content of the file are read from Cloud in the form of stream. The meta information for the files(like folder hierarchy) are locally available
I am using DotNetZip library to achieve the task. The code is as following:
long length = default(long);
Stream fileReadStream;
long Space = default(long);
string tempZipFile = string.Empty;
FileZipStatus oldStatue = new FileZipStatus();
byte[] Buffer = new byte[1024 * 1024];
if (zipFileName != null && !zipFileName.ToUpper().EndsWith(".ZIP")) zipFileName += ".zip";
string strTempFolder = "";
using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
{
try
{
strTempFolderPath = tempZipOutPutFilePath + "\\";
string strTempFolderName = DateTime.Now.Ticks.ToString();
strTempFolder = strTempFolderPath + strTempFolderName;
if (userFileList.Count > 0)
{
if (Directory.Exists(strTempFolder))
{
Directory.Delete(strTempFolder);
}
Directory.CreateDirectory(strTempFolder);
}
foreach (UserFile userFile in userFileList)
{
WebResponse response = null;
try
{
WebRequest request = null;
IDictionary<string, object> _dictionary = new Dictionary<string, object>();
/// First
FileSystemEnum fileSysEnum = FileSystemBase.GetFileSystemEnumByStorageId(userFile.StorageId);
IFileSystemLib ifileSystemLocal = FileSystemFactory.GetSpecificInstance(fileSysEnum);
fileReadStream = ifileSystemLocal.GetFile(userFile.FilePath, userFile.GuidName, ref request, ref response, _dictionary);
long filesize = default(long);
long.TryParse(ifileSystemLocal.GetFileContentLength(userFile.FilePath, userFile.GuidName).ToString(), out filesize);
Space = (Space > default(long)) ? (Space + filesize) : filesize;
//Now we have to store the data, so that we must access the file
int dataToRead;
FileStream writeStream = new FileStream(strTempFolder + "\\" + userFile.FileName, FileMode.Create, FileAccess.Write);
while ((dataToRead = fileReadStream.Read(Buffer, 0, Buffer.Length)) > 0)
{
writeStream.Write(Buffer, 0, dataToRead);
}
writeStream.Close();
zip.AddFile(strTempFolder + "\\" + userFile.FileName, userFile.RelativePath);
fileReadStream.Close();
}
catch (Exception ex)
{
LogManager.Trace(ex, "ZIpping Block - ZIPFileName", zipFileName + "File to zip" + userFile.GuidName);
}
finally
{
if (response != null) response.Close();
}
}
}
catch (Exception ex)
{
_currentStatus = FileZipStatus.NotAvailable;
oldStatue = UpdateZipStatus(ObjectZipID, Space, FileZipStatus.Failed);
throw ex;
}
finally
{
}
try
{
zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G");
zip.MaxOutputSegmentSize = 200 * 1024 * 1024; // 200 mb
zip.Save(strTempFolderPath + "\\" + zipFileName);
oldStatue = UpdateZipStatus(ObjectZipID, Space, FileZipStatus.Available);
length = new FileInfo(strTempFolderPath + "\\" + zipFileName).Length;
_currentStatus = FileZipStatus.Available;
// deleting temp folder
Directory.Delete(strTempFolder, true);
}
catch (Exception ex)
{
_currentStatus = FileZipStatus.NotAvailable;
oldStatue = UpdateZipStatus(ObjectZipID, Space, FileZipStatus.Failed);
length = default(long);
throw ex;
}
}
There are a limitation of the DotNetZip libray used in the above code.
It either needs
a) files saved on disk as input. In that case folder hierarchy information could be passed for each file.
or
2) if stream is passed as input, folder hierarchy information could NOT be passed for file.
I need to pass in the folder hierarchy information for each file as well as read the input from stream. As the zip content could be huge(could exceed 10 GB),
do not want to save the files on temporary storage in web server. Can Anyone help like how to pass folder hierarchy when creating zip file? thanks
i got the solution. here is the code
private void button2_Click(object sender, EventArgs e)
{
using (SqlConnection sqlConn = new SqlConnection(#"Data Source=BBATRIDIP\SQLSERVER2008R2;Initial Catalog=test;Integrated Security=True"))
{
string query = String.Format(#"SELECT [FilePath],[FileName],[FileData] FROM [TestTable]");
SqlCommand cmd = new SqlCommand(query, sqlConn);
cmd.Connection.Open();
System.IO.MemoryStream memStream = null;
ZipFile zip = new ZipFile();
zip.MaxOutputSegmentSize = 1024 * 1024; // 1MB each segment size would be
// the above line would split zip file into multiple files and each file
//size would be 1MB
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
byte[] data = (byte[])reader["FileData"];
memStream = new System.IO.MemoryStream(data);
string strFile = reader["FilePath"].ToString() + "\\" + reader["FileName"].ToString();
ZipEntry ze = zip.AddEntry(strFile, memStream);
}
}
zip.Save(#"e:\MyCustomZip.zip");
memStream.Dispose();
MessageBox.Show("Job Done");
// here u can save the zip in memory stream also there is a overload insteaa of saving in HD
}
}
this approach stores the zip content in memory. Hence, when the zip content is huge, say exceeds 5 GB then then it crashes. Need to write to fileOutputStream mapped to physical file
I want to take (upload) a file to a specific folder that I have created in my project (on local computer not a server!).
Here is the code that I am using:
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("images/" + filename));
I have added the Fileupload, and the code above in a button. But the code won't work. What's the problem?
I also used this form:
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("~DesktopModules/UshtrimiDyte/images/" + filename));
I also used it with double back slashes, but that didn't work either. How can I solve my problem?
Try the above
string path = Server.MapPath("~DesktopModules/UshtrimiDyte/images/" + filename);
System.IO.Stream myStream;
Int32 fileLen;
byte[] Input = null;
fileLen = FileUpload1.PostedFile.ContentLength;
if (fileLen > 0)
{
Input = new Byte[fileLen];
myStream = FileUpload1.FileContent;
myStream.Read(Input, 0, fileLen);
string I_Docx_type = FileUploadFieldDoc.FileName.Substring(FileUpload1.FileName.LastIndexOf(".") + 1);
WriteToFile(path + "." +I_Docx_type, ref Input);
path += "." + I_Docx_type;
}
method
private void WriteToFile(string strPath, ref byte[] Buffer)
{
// Create a file
System.IO.FileStream newFile = new System.IO.FileStream(strPath, System.IO.FileMode.Create);
// Write data to the file
newFile.Write(Buffer, 0, Buffer.Length);
// Close file
newFile.Close();
}
I am using the SharpZipLib open source .net library from www.icsharpcode.net
My goal is to unzip an xml file and read it into a dataset. However I get the following error reading the file into a dataset: "Data at the root level is invalid. Line 1, position 1."
I believe what is happening is the unzipping code is not releasing the file for the following reasons.
1.) If I unzip the file and exit the application. When I restart the app I CAN read the unzipped file into a dataset.
2.) If I read in the xml file right after writing it out (no zipping) then it works fine.
3.) If I write the dataset to xml, zip it up, unzip it, then attempt to read it back in I get the exception.
The code below is pretty straight forward. UnZipFile will return the name of the file just unzipped. Right below this call is the call to read it into a dataset. The variable fileToRead is the full path to the newly unzipped xml file.
string fileToRead = UnZipFile(filepath, DOViewerUploadStoreArea);
ds.ReadXml(fileToRead )
private string UnZipFile(string file, string dirToUnzipTo)
{
string unzippedfile = "";
try
{
ZipInputStream s = new ZipInputStream(File.OpenRead(file));
ZipEntry myEntry;
string tmpEntry = String.Empty;
while ((myEntry = s.GetNextEntry()) != null)
{
string directoryName = dirToUnzipTo;
string fileName = Path.GetFileName(myEntry.Name);
string fileWDir = directoryName + fileName;
unzippedfile = fileWDir;
FileStream streamWriter = File.Create(fileWDir);
int size = 4096;
byte[] data = new byte[4096];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0) { streamWriter.Write(data, 0, size); }
else { break; }
}
streamWriter.Close();
}
s.Close();
}
catch (Exception ex)
{
LogStatus.WriteErrorLog(ex, "ERROR", "DOViewer.UnZipFile");
}
return (unzippedfile);
}
Well, what does the final file look like? (compared to the original). You don't show the zipping code, which might be part of the puzzle, especially as you are partially swallowing the exception.
I would also try ensuring everything IDisposable is Dispose()d, ideally via using; also - in case the problem is with path construction, use Path.Combine. And note that if myEntry.Name contains sub-directories, you will need to create them manually.
Here's what I have - it works for unzipping ICSharpCode.SharpZipLib.dll:
private string UnZipFile(string file, string dirToUnzipTo)
{
string unzippedfile = "";
try
{
using(Stream inStream = File.OpenRead(file))
using (ZipInputStream s = new ZipInputStream(inStream))
{
ZipEntry myEntry;
byte[] data = new byte[4096];
while ((myEntry = s.GetNextEntry()) != null)
{
string fileWDir = Path.Combine(dirToUnzipTo, myEntry.Name);
string dir = Path.GetDirectoryName(fileWDir);
// note only supports a single level of sub-directories...
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
unzippedfile = fileWDir; // note; returns last file if multiple
using (FileStream outStream = File.Create(fileWDir))
{
int size;
while ((size = s.Read(data, 0, data.Length)) > 0)
{
outStream.Write(data, 0, size);
}
outStream.Close();
}
}
s.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return (unzippedfile);
}
It could also be that the problem is either in the code that writes the zip, or the code that reads the generated file.
I compared the original with the final using TextPad and they are identical.
Also I rewrote the code to take advantage of the using. Here is the code.
My issue seems to be centered around file locking or something. If I unzip the file quit the application then start it up it will read find.
private string UnZipFile(string file, string dirToUnzipTo)
{
string unzippedfile = "";
try
{
using (ZipInputStream s = new ZipInputStream(File.OpenRead(file)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = dirToUnzipTo;
string fileName = Path.GetFileName(theEntry.Name);
string fileWDir = directoryName + fileName;
unzippedfile = fileWDir;
if (fileName != String.Empty)
{
using (FileStream streamWriter = File.Create(fileWDir))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
}
}
catch (Exception ex)
{
LogStatus.WriteErrorLog(ex, "ERROR", "DOViewer.UnZipFile");
}
return (unzippedfile);
}
This is a lot simpler to do with DotNetZip.
using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
zip.ExtractAll(TargetDirectory);
}
If you want to decide on which files to extract ....
using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
foreach (ZipEntry e in zip)
{
if (wantThisFile(e.FileName)) e.Extract(TargetDirectory);
}
}
If you would like to overwrite existing files during extraction:
using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
zip.ExtractAll(TargetDirectory, ExtractExistingFileAction.OverwriteSilently);
}
Or, to extract password-protected entries:
using (ZipFile zip = ZipFile.Read(ExistingZipFile))
{
zip.Password = "Shhhh, Very Secret!";
zip.ExtractAll(TargetDirectory, ExtractExistingFileAction.OverwriteSilently);
}