create Directory and if exist then rename it - asp.net

i am developing application in which i want that if user create folder and if it is already present then folder should automatically renamed by appending number to folder name
suppose server has folder with name Time now if user again creates folder than it new folder will be Time1 again user creates folder with same name(Time or Time1) than new Folder should be created with Time2 and so on... This is what i have done so far but recursion always return wrong value.
public string checkIfExist(String path, String ProgramName, int itteration,out string strFolderName)
{
String uploadPath = "";
strFolderName = "";
String Mappath =HttpContext.Current.Server.MapPath(path);
if (Directory.Exists(Mappath))
{
String Path = HttpContext.Current.Server.MapPath((path + "" + ProgramName.Replace(" ", "_")));
// uploadPath += ++itteration ;
if (Directory.Exists(Path))
{
ProgramName += ++itteration;
strFolderName = ProgramName;
uploadPath = checkIfExist(path, ProgramName, itteration,out strFolderName);
}
}
return ProgramName;
}

Perhaps you could adapt this, to your need. I wrote it on the fly based on a piece of code I remember in an old file manager I was using in some projects, so please test it. This doesn't include creation and so on, based on your example I'm sure you can add that yourself but if you need help just comment below.
The idea is to pass the original name of the directory you want, and then return an appropriate new name if it exists, such as Test(1), Test(2), Test(n). Then once you get the name you need, you can create it directly.
protected string GetUniqueDirectoryName(string dirName)
{
string newDirName = dirName;
for (int i = 1; Directory.Exists(Server.MapPath("PATH_HERE") + newDirName); i++)
{
newDirName = string.Format("{0}({1})", dirName, i);
}
return newDirName;
}
Note: You will need to include System.IO and probably use HttpContext.Current.Server.MapPath instead of Server.MapPath

I don't know if I really understand what you are trying to do, but I think using recursion here is a little overkill. Try something like this:
string dirName = "Time";
int counter = 0;
string dir = dirName;
while(Directory.Exists(dir))
{
dir = String.Format("{0}{1}", dirName, (++counter).ToString());
}
Directory.CreateDirectory(dir);

Related

How change server map path and file name when file uploaded in asp.net mvc?

I am trying to save picture in folder and store path in database using entity framework in asp.net mvc 5.
I did it but I have some problems .
image path in DB saved like this :
C:\Users\Shima\Documents\Visual Studio 2013\Projects\NP1\NP1\Images\SubGoods\2.jpg
How can I change it to: ~/Images/SubGoods/2.jpg ??
and I want to change image name to it's primary key id and I used pic =Convert.ToString( subgood.SubGoodID); to do it, but it saves Zero :
C:\Users\Shima\Documents\Visual Studio 2013\Projects\NP1\NP1\Images\SubGoods\0
It saves always 0 .I know that's because Primary key in that line not generated yet . where of my codes primary Key id generated ?
public ActionResult AddSubGood(SubGood subgood, HttpPostedFileBase UploadImage)
{
var MainGoodId = subgood.FKMainGoodID;
SubGoodRepositories blSubGood = new SubGoodRepositories();
string path="";
if (UploadImage != null)
{
string pic = System.IO.Path.GetFileName(UploadImage.FileName);
pic =Convert.ToString( subgood.SubGoodID);
path = System.IO.Path.Combine(
Server.MapPath("~/Images/SubGoods"), pic);
}
if (ModelState.IsValid)
{
subgood.FKMainGoodID = MainGoodId;
UploadImage.SaveAs(path);
subgood.SubGoodImage = path;
if (blSubGood.Add(subgood))
{
return JavaScript("alert('saved');");
}
else
{
return JavaScript("alert('didn't saved');");
}
}
else
{
return JavaScript("alert('error');");
}
}
You should save only the file name:
var fileName = Path.GetFileName(UploadImage.FileName);
Then when you want to fetch the file for user you can simply address the file name with specific path:
<img src="~/Content/Uploaded/#item.fileName" .../>
You can also generate a random file name using Guid:
var rondom = Guid.NewGuid() + fileName;
Server.MapPath will return you Virtual path(which you don't needed) , you can create another variable and concatenate like this :
string DbPath = "~/Images/SubGoods/"; // better to store in web.config file
DbPath = DbPath + ""//here you can query in table and find the last inserted primary key and increment it with '1'

MultipartFormDataStreamProvider Cleanup

If files are posted to my webapp, then I read them via MultipartFormDataStreamProvider.FileData.
I Initialize the provider like this:
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
And the provider nicely stores them as "~App_Data/BodyPart_{someguid}"
But how do I clean up those files after I'm done with them?
I know this question is old, but the best way I found to delete the temporary file was after processing it.
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
foreach (var file in provider.Files)
{
// process file upload...
// delete temporary file
System.IO.File.Delete(file.LocalFileName);
}
You could delete all files that are older than a certain timespan. e.g.
private void CleanTempFiles(string dir, int ageInMinutes)
{
string[] files = Directory.GetFiles(dir);
foreach (string file in files)
{
var time = File.GetCreationTime(file);
if (time.AddMinutes(ageInMinutes) < DateTime.Now)
{
File.Delete(file);
}
}
}
Then call it with something like:
CleanTempFiles(root, 60); // Delete all files older than 1 hour

Creating dynamic multi language website

I'm planning to implement a multi language website, so my first ideas were to use the resx files, but I have a requirements to let every text editable from the administration,
can i do such a feature with resx files or should I store them in a database (schemaless) or is there a better way to do this?
you can use xml or sql tables.
you should prepare a page for administrator and list all the words for translate.
base of language administrator logged on , update the translation of words into your table or xml file.
additional , for best performance load each language words to system catch .
write some code like this for entering words into table or xml.
<%=PLang.GetString("YourWordInEnglish")%>
in your aspx
...................
public static string GetString(string word)
{
try
{
if (String.IsNullOrWhiteSpace(word)) return "";
Dictionary<string, string> resourcesDictionary = GetResource(GetLanguageID());
if (resourcesDictionary != null)
{
if (!resourcesDictionary.ContainsKey(word.ToLower()))
{
Expression exp = new Expression();
exp.Word = exp.Translation = word;
exp.LanguageID = GetLanguageID();
exp.SiteID = Globals.GetSiteID();
if (exp.SiteID == 0 && exp.LanguageID == 0)
return word;
if (FLClass.createExpression(exp, ref resourcesDictionary) > 0)
return resourcesDictionary[word];
else
return word;
}
return resourcesDictionary[word.ToLower()];
}
else
return word;
}
catch
{
return word;
}
}
...................
function for edit
public class ViewExpressionListEdit : BaseWebService
{
[WebMethod(EnableSession = true)]
public bool updateExpression(ExpressionService expressionService)
{
Expression expression = new Expression();
expression.ExpressionID = expressionService.ExpressionID;
expression.Translation = expressionService.Translation;
expression.LanguageID = expressionService.LanguageID;
expression.SiteID = Globals.GetSiteID();
return FLClass.updateExpression(expression);
}
}
You can use XML files for translations, parse them on application startup and store translations in cache. You can use the FileSystemWatcher class to see when someone updates the files and then invalidate the cache.

MethodAccessException when updating a record in sqlite db

I encounter this exception when I try to updating a record with following statement.
UPDATE GroupTable SET groupId=100 WHERE groupId=101
I tested the statement under SQLite Manager of Firefox plug-in, and it works.
The error message is as following image. It crashed at the os_win_c.cs, the method named getTempname().
Well, I modified the original codes and fixed this bug.
The Path.GetTempPath() doesn't work because the sandbox enviroment. It has no access right.
I fixed by following codes. And it works now.
static int getTempname(int nBuf, StringBuilder zBuf)
{
const string zChars = "abcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder zRandom = new StringBuilder(20);
i64 iRandom = 0;
for (int i = 0; i < 20; i++)
{
sqlite3_randomness(1, ref iRandom);
zRandom.Append((char)zChars[(int)(iRandom % (zChars.Length - 1))]);
}
//! Modified by Toro, 2011,05,10
string tmpDir = "tmpDir";
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
store.CreateDirectory(tmpDir);
//zBuf.Append(Path.GetTempPath() + SQLITE_TEMP_FILE_PREFIX + zRandom.ToString());
zBuf.Append(tmpDir + "/" + SQLITE_TEMP_FILE_PREFIX + zRandom.ToString());
return SQLITE_OK;
}
The above patch will result in an extra folder tmpDir in the isolatedstorage, and the temp files won't be deleted automatically, so it needs to be delete by self. I tried to delete those files in tmpDir in the method of winClose inside os_win_c.cs, and I found it will result in crash when I do VACUUM. Finally, I delete those tmp files when I closed the database. The following is a Dispose method in SQLiteConnection class.
public void Dispose()
{
if (_open)
{
// Original codes for close sqlite database
Sqlite3.sqlite3_close(_db);
_db = null;
_open = false;
// Clear tmp files in tmpDir, added by Toro 2011,05,13
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
string tmpDir = "tmpDir";
if (store.DirectoryExists(tmpDir) == false) return;
string searchPath = System.IO.Path.Combine(tmpDir, "*.*");
foreach (string file in store.GetFileNames(searchPath)) {
store.DeleteFile(System.IO.Path.Combine(tmpDir, file));
}
}
}

Need to find the length of audio file in minutes in asp.net

I have asp.net application in which i am uploading audio files by converting them into the stream and upload to the database.But not able to find the length of the audio file into minutes.Here problem is that my asp.net application is present in the cloud.For uploading i am using upload file control of asp.net.Please suggest solution for this.
You may look at taglib#
I would have expected that you can calculate this from the bit rate and the file length: (file.lenghtInBits / kbsp ) / 60 = minutes.
rather assumes that you can get the bit rate from the file header though.
You will need to reference Windows Media Player. Go to Com Add-ins to add the wmp.dll to your project.
string Duration = null;
WMPLib.WindowsMediaPlayer w = new WMPLib.WindowsMediaPlayer();
WMPLib.IWMPMedia mediaFile = w.newMedia(Filename);
if (mediaFile != null) {
Duration = mediaFile.durationString;
}
w.close();
You could use the NAudio library as suggested in this answer to a similar SO question.
We can do it easily by given below code
private string GetDuration(string FileFullPath)
{
string duration = "";
string fName = FileFullPath.Substring(FileFullPath.LastIndexOf("\\") + 1);
string filePath = FileFullPath.Substring(0, FileFullPath.LastIndexOf("\\"));
Shell32.Shell shell = new Shell32.ShellClass();
Shell32.Folder folder = shell.NameSpace(filePath);
Shell32.FolderItem folderItem = folder.ParseName(fName);
if (folderItem != null)
{
duration = folder.GetDetailsOf(folderItem, 21);
}
folderItem = null;
folder = null;
shell = null;
return duration;
}
TimeSpan span= GetWavFileDuration(filePath + "\" + fileName);
string spanSeconds = span.TotalSeconds.ToString();
string[] spanSecondsArray=spanSeconds.Split('.');
spanSeconds = spanSecondsArray[0].ToString();
public static TimeSpan GetWavFileDuration(string fileName) {
WaveFileReader wf = new WaveFileReader(fileName);
return wf.TotalTime;
}
You can use this library for getting the Audio file duration

Resources